#!/usr/bin/perl
# 
# ***** BEGIN LICENSE BLOCK *****
# Version: MPL 1.1
# 
# The contents of this file are subject to the Mozilla Public License
# Version 1.1 ("License"); you may not use this file except in
# compliance with the License. You may obtain a copy of the License at
# http://www.zimbra.com/license
# 
# Software distributed under the License is distributed on an "AS IS"
# basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
# the License for the specific language governing rights and limitations
# under the License.
# 
# The Original Code is: Zimbra Collaboration Suite Server.
# 
# The Initial Developer of the Original Code is Zimbra, Inc.
# Portions created by Zimbra are Copyright (C) 2005, 2006 Zimbra, Inc.
# All Rights Reserved.
# 
# Contributor(s):
# 
# ***** END LICENSE BLOCK *****
# 

use strict;

my $sfilename=$ARGV[0];
my $dfilename=$ARGV[1];

my $id = `whoami`;
chomp $id;
if ($id ne "zimbra") {
    print STDERR "Error: must be run as zimbra user\n";
	exit (1);
}

if ( $dfilename eq "" ) {
	print STDERR "Usage: $0 <source> <dest>\n\n";
	exit (1);
}

if ( ! -f $sfilename ) {
	print STDERR "Error: $sfilename does not exist\n]n";
	exit (1);
}

unlink ($dfilename);

if ( -f $dfilename ) {
	print STDERR "Error: Can't remove $dfilename\n\n";
	exit (1);
}

# @@var@@ for zmlocalconfig variables
# %%var%% for zmprov variables

open (SOURCE, $sfilename) or die "Can't open $sfilename: $!";
my @slines = <SOURCE>;
close SOURCE;

open (DEST, ">$dfilename");

my $host = "";

foreach my $sline (@slines) {
	while ($sline =~ m/\@\@([^\@]+)\@\@/g) {
		my $sr = $1;
		my $rep=`/opt/zimbra/bin/zmlocalconfig -q -m nokey $sr`;
		chomp $rep;
		$sline =~ s/\@\@$sr\@\@/$rep/g;
	}

	# We support parsing for the zmprov functions.
	# Normal parsing uses gcf
	# Functions supported:
	#	comment(args) - replace with comment char "#" if true (or value exists)
	#
	# args supported:
	#	SERVER:key - use command gs with zimbra_server_hostname, get value of key
	#
	while ($sline =~ m/%%([^%]+)%%/g) {
		my $sr = $1;
		my $rep;
		if ($sr =~ m/^comment/) {
			my ($cmd, $key, $pattern) = ($sr =~ m/comment ([^:]+):(\S+) (.*)/);
			if ($cmd eq "SERVER") {
				if ($host eq "") {
					$host=`/opt/zimbra/bin/zmlocalconfig -q -m nokey zimbra_server_hostname`;
					chomp $host;
				}
				$rep = `/opt/zimbra/bin/zmprov -l gs $host | sed -e 's/[^ ]* //' | grep $pattern`;
				if ($rep ne "") {
					$rep = "#";
				}
			}
		} else {
			$rep=`/opt/zimbra/bin/zmprov -l gcf $sr | sed -e 's/[^ ]* //'`;
			chomp $rep;
		}
		$sline =~ s/%%$sr%%/$rep/g;
	}

	print DEST $sline;
}
close DEST;


