#!/bin/bash
#
# File: /usr/local/bin/gpgsu
#
# Process eMail with GnuPG.
#
#    Copyright (C) 2008  Juergen Kaesmann (JK)
#    Modified 2013 by Ingo Kaesmann (inka)
#
#    This program is free software; you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation; either version 2 of the License, or
#    (at your option) any later version.
#
#    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
#
# Exit codes:
# Standard
# 30 = gpgswitch locked, no execution

##############################################################################
# SOURCE FILES

. /usr/local/etc/main-inka-sh.conf			# config main
#. $LLIBDIR/func-std.sh					# functions general

##############################################################################
# DECLARATION OF VARIABLES

# STRINGS
pkgname=ksm-gpgswitch-inka
version=$(grep "^VERSION" $PROGREG/$pkgname.inf | cut -f 2)	# version
#lib_func_std_sh_needed=0.2.0
#lib_func_ip_sh_needed=0.2.0
#lib_func_cddvd_sh_needed=0.3.0
scriptname=`basename $0`				# name of script
tempfile=$TEMPDIR/$scriptname.$UID.$$.tmp		# temporary file
infolog="logger -p user.info -t $scriptname --"		# log info messages
errlog="logger -p user.err -t $scriptname -- ERROR:"	# log error messages
debuglog="logger -p user.debug -t $scriptname -- DEBUG:" # log debug messages
debug=no						# debug=yes/no
verbose=''						# verbose=yes/''/no
cmd_found=no						# cmd_found=yes/no
opt_found=no						# opt_found=yes/no
cmd=''							# cmd
#------------------End Of Standard Variables----------------------------------
debug1=no	# debug1=yes/no, additional debug output goes to debuglog
debug2=no	# debug2=yes/no, redir output to stdout
sendmail='/usr/sbin/sendmail -oem -oi'			# how to call sendmail
ffile="/var/local/$pkgname/gpgswitch.on"		# Flag file
gpguserfile='/usr/local/etc/gpguser.conf'		# user, id, key file
gpgswitch=/usr/local/bin/gpgswitch
gpgsw_mail=''
clp=''							# cmd line parameters
user=''							# gpgswitch runs for
global_result=''					# result of functions

# NUMBERS
err=0

##############################################################################
# FUNCTIONS

#-----------------------------------------------------------------------------
function helptext ()
{
# Output helptext
# Uses: cat
# Return codes:
# Standard

if [ "$debug" == "yes" ]; then				# DEBUG
	$debuglog helptext: $# $@
fi

cat <<EOT

Aufruf: $scriptname [OPTION | PARAMETER...]
Wrapper fuer gpgswitch, Phase 2

-h, --help      Hilfe anzeigen und beenden
 --version      Versionsinformationen anzeigen und beenden

PARAMETER       Parameter fuer 'sendmail': {-f ABSENDER EMPFAENGER}

EOT

return
}
#-----------------------------------------------------------------------------
function get_user ()
{
# get the user of an key id out of gpguserfile
# par1 = key id
# output goes to global var 'global_result'
# Uses: cat, cut, grep
# Return codes:
# Standard

if [ "$debug" == "yes" ]; then				# DEBUG
	$debuglog get_user: $# $@
fi

local keyid s ret
keyid=$1
s=''
#l=0
ret=0

#s=`cat $gpguserfile | cut -d ';' -f 2 | grep -n -m 1 "$keyid"`
s=`grep -m 1 "$keyid" $gpguserfile`
ret=$?
if [ "$ret" -eq 0 ]; then
	#l=${s%%:*}					# rm ':*' from EOL
	#s=`Get_Lines $gpguserfile $l $l`
	#ret=$?
	#if [ "$ret" -eq 0 ]; then
		global_result=${s%%;*}
	#fi
fi

return $ret
}
#-----------------------------------------------------------------------------
function main_proc ()
{
# main part of the program
# pars = all cmd line pars but without $1=gpgsw_mail
# works with respect to the flagfile 'ffile'
# Uses: cat, echo, su
# Return codes:
# Standard

if [ "$debug" == "yes" ]; then				# DEBUG
	$debuglog main_proc: $# $@
fi

local s ret
s=$2							# sender key id
ret=0

if [ -e $ffile ]; then					# gpgswitch is active
	get_user $s
	ret=$?
	if [ "$ret" -eq 0 ]; then			# gpg user found
		user=$global_result
		if [ "$debug2" == "yes" ]; then		# DEBUG2
			echo "-s $clp"
			cat $gpgsw_mail
		else
			if [ "$debug1" == "yes" ]; then
				$debuglog main_proc: active user=$user gpgsw_mail=$gpgsw_mail clp=$clp
			fi

			su $user -c "$gpgswitch -s $gpgsw_mail $clp"
		fi
		ret=$?
	else						# no gpg user found
		if [ "$debug2" == "yes" ]; then		# DEBUG2
			echo "-s $clp"
			cat $gpgsw_mail
		else
			cat $gpgsw_mail | $sendmail $clp
		fi
		ret=$?
	fi
else							# gpgswitch inactive
	if [ "$debug2" == "yes" ]; then			# DEBUG2
		echo "-s $clp"
		cat $gpgsw_mail
	else
		if [ "$debug1" == "yes" ]; then
			$debuglog main_proc: inactive gpgsw_mail=$gpgsw_mail clp=$clp
		fi

		cat $gpgsw_mail | $sendmail $clp
	fi
	ret=$?
fi

return $ret
}
##############################################################################
# PARSE COMMANDLINE

# Read the cmd, all options with args and all additional args into variables.
# Stop parsing after last parameter.
# Try to do a check on all parameters and version numbers.
# Handle cmds -h and -V directly.
# Exit on error.

if [ "$debug" == "yes" ]; then				# DEBUG
	$debuglog Parse Commandline: $# $@
fi

# get command (1. cmdline parameter)
case $1 in
  -h|--help)	cmd='-h'; shift; cmd_found='yes';;	# cmd -h
  --version)	cmd='--v'; shift; cmd_found='yes';;	# cmd --v
#  -s)	cmd="$1"; shift; cmd_found='yes';;		# cmd found
#  *)	echo "Error - unknown command $1 !" >&2		# error
#	$errlog unknown command $1
#	exit 1;;
esac

# get options
#while [ "${1:0:1}" == "-" ]; do			# get all options
#	case $1 in
#	  -d|--debug)	debug=yes;;			# option -d
#	  -q|--quiet)	verbose=no;;			# option -q
#	  -v|--verbose)	verbose=yes;;			# option -v
#	  *)	echo "Error - unknown option $1 !" >&2	# error
#		$errlog unknown option $1
#		exit 1;;
#	esac
#	shift
#	opt_found=yes
#done

# handle standard commands -h, --v
case $cmd in
  -h)	helptext; exit 0;;				# give help
  --v)	echo "$scriptname (${pkgname}) $version"; exit 0;; # output version
esac

# check libraries S I C
#Check_Libs

# check version of config files
#if [ "$version" != "$sample_cnf" ] || [ "$version" != "$sample_rc" ]; then
#	if [ "$verbose" != no ]; then
#		echo "Error in version of config files!" >&2
#	else
#		$errlog version of config files differ
#	fi
#	exit 3
#fi

# check arguments after commands and options
#case "$cmd" in
#  -x)	if [ "$#" -eq 1 ]; then				# parameter count ok
#		arg1="$1"
#		shift
#	else						# error in param count
#		echo "Error in parameter count!" >&2
#		$errlog wrong parameter count
#		exit 2
#	fi;;
#  *)	if [ "$#" -ne 0 ]; then				# error in param count
#		echo "Error in parameter count!" >&2
#		$errlog wrong parameter count
#		exit 2
#	fi;;
#esac

##############################################################################
# MAINPROGRAM

if [ "$debug" == "yes" ]; then				# DEBUG
	$debuglog Main: $# $@
fi

# Check what to do (initial cmds, options and args are removed from cmdline)
gpgsw_mail="$1"
shift
clp="$@"						# cmd line parameters
main_proc $clp
err=$?

exit $err
