#!/bin/sh
#
# $OpenBSD: gpgzip,v 1.1 2005/05/31 09:09:30 db Exp $
#
# AMANDA gzip wrapper for GPG encrypted backups
# modified version from jaf@uchicago.edu

# enable for debugging
#set -x

# Set default configuration variables and locations for binaries
config="@SYSCONFDIR@/amanda/amanda.gpg.conf"
debug_bin="/usr/bin/logger"

gzip_bin="/usr/bin/gzip"
gzip_flags="$@"

gpg_bin="@LOCALBASE@/bin/gpg"
gpg_encrypt_flags="--no-tty --batch --no-secmem-warning --no-verbose -e"
gpg_decrypt_flags="--no-verbose --no-greeting --no-secmem-warning \
		   --no-tty --batch -d"


# Encrypt the data stream and feed it to gzip for final compression.
# NOTE: gpg will compress the data by default with the first supported
# algorithm found in the recipient key settings, defaults to zlib, ZIP.
# Encrypting the files first is suboptimal for further compression, but
# otherwise gpg will complain about tapered data when restoring with
# the AMANDA utilities.
dump() {
    ${gpg_bin} --homedir=${gpg_home} -r ${gpg_id} \
        ${gpg_encrypt_flags} | \
        ${gzip_bin} ${gzip_flags} >&1
}

# Unzip and decrypt the data stream
restore() {
    ${gzip_bin} ${gzip_flags} | \
	${gpg_bin} ${gpg_decrypt_flags} --homedir=${gpg_home} \
	-r ${gpg_id} >&1
}


# Sane environment?
if [ ! -f ${config} ]; then
    ${debug_bin} "Configuration file ${config} not found."
    exit 1
else
    . ${config}
    if [ "$gpg_id" = "" ]; then
	${debug_bin} "ERROR: gpg_id variable not set in ${config}."
	exit 1
    elif [ "$gpg_home" = "" ]; then
	${debug_bin} "ERROR: gpg_home variable not set in ${config}."
	exit 1
    fi
fi

# Called with -dc as argument for restore. Checking for d will suffice.
while getopts "d" arg
do
	case $arg in
	    d)  
	    	restore
		break
		;;
	    *)
	    	dump
		break
		;;
	esac
done

exit 0
