#!/bin/bash
#
#  2018-11-19 stvo
#  replace couriertls with stunnel
#  in qmail-smtpSd (port 465)
#  $Id: couriertls-to-stunnel.sh,v 1.2 2018/11/21 09:34:19 testx Exp testx $
#
set -Ceuo pipefail
#set -x

type grep
type mv
type chmod
type mktemp
type curl
type svc

function errfunc ()
{
   echo "error: <$errmsg>"
}

trap "errfunc" ERR

tmpfile=
function exitfunc ()
{
   test -f "$tmpfile" && rm -f "$tmpfile" || true
}
trap "exitfunc" EXIT

stunnel=/usr/local/pd-admin2/bin/stunnel
errmsg="$stunnel does not exist or is not executable.
Please upgrade your server to at least SE 0.320."
test -x $stunnel

errmsg="cannot execute stunnel."
if ! $stunnel -version &>/dev/null; then
   $stunnel -version
fi

servicedir=/service/qmail-smtpSd
runfile="$servicedir/run"
errmsg="$runfile does not exist"
test -f $runfile

errmsg="$runfile uses stunnel already"
grep -q $stunnel $runfile && false

runfile_backup="${runfile}_couriertls"
errmsg="runfile is already backed up: $runfile_backup"
test -f $runfile_backup && false

errmsg="could not create tmpfile"
tmpfile=$(mktemp run.XXXXXX)

errmsg="could not download http://download.pd-admin.de/run-465"
curl download.pd-admin.de/run-465 >| "$tmpfile"

errmsg="could not chmod tmpfile"
chmod 0750 "$tmpfile"

errmsg="could not backup runfile"
ln $runfile $runfile_backup

errmsg="could not move tmpfile"
mv "$tmpfile" $runfile

errmsg="could not restart service"
svc -d $servicedir
svc -u $servicedir

echo "success"
