#!/usr/bin/perl
#
# Copyright (c) 2006 Zmanda Inc.  All Rights Reserved.
#
# This program is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License version 2 as published
# by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
# or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
# for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
#
# Contact information: Zmanda Inc, 505 N Mathlida Ave, Suite 120
# Sunnyvale, CA 94085, USA, or: http://www.zmanda.com
#

# This file contains data encryption plugin template that can be used 
# with Zmanda Recovery Manager (ZRM) for MySQL. For more information about the
# product, please see http://mysqlbackup.zmanda.com/
#
# This plugin will encrypt the data on stdin and write the encrypted 
# data to stdout
# 
# How to use this plugin
# ----------------------
# 1. Create a file called .passphrase in /etc/mysql-zrm/<backup set name>
#    directory and put the passphrase to be used for encryption in this file.
#
# 2. chmod 700 /etc/mysql-zrm/<backup set name>/.passphrase
#
# 3. Modify the mysql-zrm.conf file in the relavant backup-set directory
#    (/etc/mysql-zrm/<backup set name>/mysql-zrm.conf) and add the
#    following line to the configuration file.
#
#    encrypt-plugin="/usr/share/mysql-zrm/plugins/<backup set name>/encrypt-plugin.pl"
# 4. Modify the mysql-zrm.conf file mentioned above and add the following line
#
#    passfile="/etc/mysql-zrm/<backup set name>/.passphrase"

use strict;

#If a different file is to be used, specify passfile in mysql-zrm.conf
my $PASSFILE="/etc/mysql-zrm/.passphrase";

$ENV{"PATH"}="/usr/local/bin:/opt/csw/bin:/usr/bin:/bin:/sbin:/usr/sbin";
my $ENCRYPT_PROG="gpg";

my %config;
# This reads the conf file that is prepared by mysql-zrm.
# Please note this does not do any validation of the config file 
# pointed to by $ZRM_CONF in the enviornment
sub parseConfFile()
{
	my $fileName = $ENV{'ZRM_CONF'};
	unless( open( FH, "$fileName" ) ){
		die "Unable to open config file $fileName\n";
	}	
	my @tmparr = <FH>;
	close( FH );
	chomp( @tmparr );
	foreach( @tmparr ){
		my @v = split( /=/, $_ );
		my $v1 = shift @v;
		my $v2 = join( "=", @v );
		$config{$v1} = $v2;
	}
}

&parseConfFile( );
if( $config{"passfile"} ){
	$PASSFILE = $config{"passfile"};
}

if( ! -f $PASSFILE ){
	die "Passphrase file $PASSFILE not found";
}

my $arg = "--quiet --batch --passphrase-fd 3 3<$PASSFILE";

if( $ARGV[0] eq "-d" ){
	$arg .= " --no-mdc-warning --decrypt";
}else{
	$arg .= " --disable-mdc --symmetric --cipher-algo AES256"; 
}
my $r = system("$ENCRYPT_PROG $arg");
if( $r > 0 ){
	die "gpg failed";
}
exit( 0 );
