#!/bin/ksh

# Secured version of the tar archiving utility
# (c) Oleg Bolshakov, CBD BC, 2013
# http://www.kpda.ru

#ifdef __USAGE
#%C - secured wrapper of the tar archiving utility
#
#%C [-key=<key>] [-keygen] [<file>]
#    -key=<key>    use <key> key instead of default
#    -keygen       generate private and public keys
#
#If <file> has extension .enc then it will be unpacked. Otherwise it
#will be compressed and encoded.
#
#Be awared! To unpack encoded archive you should have two files *.enc
#and *.key. They both are created by this utility.
#endif

# Configuration area
CONF_PATH=${HOME}/.tarenc
TAR_COMP=j		# J for xz, j for bz2, z for gz, etc
#MKPASS='pwgen -yns 40 1'
MKPASS='openssl rand -base64 30'

# Help message (emulating use)
if [[ -z ${1} || ${1} == '-h' || ${1} == '-help' ]] ; then
	if [ ! -f ${0} ]; then exit 3; fi
	sed -e '/^#ifdef __USAGE$/,/^#endif$/ !d' -e 's/^#ifdef __USAGE$//' \
		-e 's/^#endif$//' -e 's/^#//' -e "s/^%C/`basename ${0}`/" ${0}
	exit 0
fi

# Switch to specific keys
if [ ${1%=*} == '-key' ] ; then
	CONF_PATH=${CONF_PATH}/${1##*=}
	shift
fi

# Set key names
KEY_PRV=${CONF_PATH}/key_dec.pem		# private
KEY_PUB=${CONF_PATH}/key_enc.pem		# public

# Generate keys
if [ ${1} == '-keygen' ] ; then

	if [ ! -d ${CONF_PATH} ] ; then
		mkdir ${CONF_PATH}
	fi

	echo Generating ${KEY_PRV}
	openssl genrsa -out ${KEY_PRV} 2048 > /dev/null 2>&1
	echo Generating ${KEY_PUB}
	openssl rsa -in ${KEY_PRV} -out ${KEY_PUB} -outform PEM -pubout > /dev/null 2>&1
	exit 0
fi

# Create secured archive
if [ ${1##*.} != 'enc' ] ; then

	if [ ! -f ${KEY_PUB} ] ; then
		echo Can\'t open public key \'${KEY_PUB}\'
		exit 1
	fi

	if [ ! -e ${1} ] ; then
		echo Can\'t open \'${1}\'
		exit 2
	fi

	PASS=`$MKPASS`
	tar c${TAR_COMP} ${1} | openssl enc -aes-256-cbc -pass pass:${PASS} -out ${1}.enc
	echo ${PASS} | openssl rsautl -encrypt -pubin -inkey ${KEY_PUB} -out ${1}.key

# Unpack secured archive
else

	if [ ! -f ${KEY_PRV} ] ; then
		echo Can\'t open private key \'${KEY_PRV}\'
		exit 1
	fi

	if [ ! -f ${1} ] ; then
		echo Can\'t open \'${1}\'
		exit 2
	fi

	PASS=`openssl rsautl -decrypt -inkey ${KEY_PRV} -in ${1%.*}.key`
	openssl enc -aes-256-cbc -d -pass pass:${PASS} -in ${1} | tar x${TAR_COMP}
fi

