#!/usr/bin/perl -wpi -0777

# we only do files with VersionWebshield v1.0 (e500 v2.0 and e250 v2.1)
# or 2.5, 2.6
next unless m{<General\b.*<Property\b[^>]*?cname="VersionWebshield"[^>]*>
	[^<]*v(?:1\.0|2\.[56])\b
	.*</General\b}sx;

# function for removing properties
sub DelProps
{
    my $s = shift @_;
    my $p = join "|", @_;
    $s =~
	s{(\n?)\s*?<Property\b[^>]*?cname="(?:$p)".*?</Property>\s*?\n?}{$1}gs;
    return $s;
}

# clean out old email alert templates
my @mailalerts = qw{
	    OutboundAlertFile
	    Outbound_StrictPartialParseYes_AlertFile
	    Outbound_StrictPartialParseNo_AlertFile
	    Outbound_TooManyAttachments_AlertFile
	    Outbound_ReplaceSize_AlertFile
	    Outbound_ReplaceAll_AlertFile
	    Outbound_ReplaceAlternate_AlertFile
	    Outbound_ReplaceName_AlertFile
	    InboundAlertFile
	    Inbound_StrictPartialParseYes_AlertFile
	    Inbound_StrictPartialParseNo_AlertFile
	    Inbound_TooManyAttachments_AlertFile
	    Inbound_ReplaceSize_AlertFile
	    Inbound_ReplaceAll_AlertFile
	    Inbound_ReplaceAlternate_AlertFile
	    Inbound_ReplaceName_AlertFile
	};
s{(<General\b.*?</General\s*>)} {DelProps($1, @mailalerts)}sxe;

# clean out old POP3 options
@pop3old = qw{
	StripAttachmentsEnable
	BadContentHandling
	LimitAcceptCount
	AcceptCount
	MaxConnections
	DefaultAcceptCount
	DefaultMaxConnections
	L[245]AcceptCount
	L[245]MaxConnections
    };
s{(<Service\b.*?\brealname="pop3-pdk".*?</Service\b)}
    {DelProps($1, @pop3old)}sxge;

# fix up streaming media settings
sub FixStream
{
    my ($s) = (@_);
    my ($flag, $list);
    # chop out AllowStreamingMedia, saving content in $flag
    $s =~ s{(\n?)\s*?<Property\b[^>]*?cname="AllowStreamingMedia"
	    [^>]*?(?:/>|>(.*?)</Property>)\s*?\n?} {$1}sx
	and $flag = $2;
    # chop out DontContentScanFileType, saving content in $list
    $s =~ s{(\n?)\s*?<Property\b[^>]*?cname="DontContentScanFileType"
	    [^>]*?(?:/>|>(.*?)</Property>)\s*?\n?} {$1}sx
	and $list = $2;
    # before 2.7 $flag didn't exist and $list empty or "audio/*" was the flag
    if ( !defined $flag || ($flag ne "true" && $flag ne "false") ) {
	# expected condition: no valid $flag - set it according to $list
	if (defined $list && $list ne "") { $flag = "true" }
	else { $flag = "false"; undef $list }	# default $list
    }
    # put in our new AllowStreamingMedia
    $s =~ s{(\n?\s*?)(?=</Service)}
	{$1\t<Property cname="AllowStreamingMedia">$flag</Property>$1}s;
    # put in our new DontContentScanFileType
    $s =~ s{(\n?\s*?)(?=</Service)}
	{$1\t<Property cname="DontContentScanFileType">$list</Property>$1}s
	    if (defined $list);
    return $s;
}
# ... fix in http in/outbound elements
s{(<Service\b[^>]*?\bname="http-from.*?</Service\s*>)}{FixStream($1)}gsxe;
