#!/bin/sh
# WARNING: This file was auto-generated. Do not edit!
#
# $Id: minisvc.in,v 1.40 2024-11-05 22:32:40+05:30 Cprogrammer Exp mbhangui $
#

#
# User Configuration
#
prefix=/usr
sysconfdir=/etc/indimail
shareddir=/usr/share/indimail
LOGDIR=/var/log/svc
libexecdir=/usr/libexec/indimail
host=x86_64-pc-linux-gnu
RCSID="# \$Id: minisvc.in,v 1.40 2024-11-05 22:32:40+05:30 Cprogrammer Exp mbhangui $"

#
# End of User Configuration
#
if [ -f /usr/bin/less ] ; then
	MORE=/usr/bin/less
else
	MORE=/usr/bin/more
fi
usage()
{
echo "Press ENTER for options, Cntrl C to quit" 1>&2
read key
$MORE <<EOF
Usage: minisvc [OPTION]

Known values for OPTION are:

--svscanlog --servicedir=service_path [--initcmd=cmmd --scanint=n --resolvconf]

  service_path - Path where supervise service will be installed
  cmmd         - Program/Script to run instead of .svscan/run
  n            - Scan interval for svscan command
  --resolvconf - mount /etc/indimail/resolv.conf as /etc/resolv.conf
                 Use if you have dnscache installed in $servicedir/dnscache

--unshare
  Use unshare to mount private /etc/resolv.conf for using local dns

--down
  Create supervisor services in down state

--rmsvc=service_name

  Disable supervise scripts for service
  service_name   - name of service with full path
                   e.g. (/service/qmail-smtpd.25)
                   (give multiple services enclosed in double quotes)
                   "/service/qmail-smtpd.25 /service/qmail-imapd.143"

--ensvc=service_name

  Enable supervise scripts for service
  service_name   - name of service with full path
                   e.g. (/service/qmail-smtpd.25)
                   (give multiple services enclosed in double quotes)
                   "/service/qmail-smtpd.25 /service/qmail-imapd.143"

--refreshsvc=service_name
  [--run-file-only] [--force]

  Enable supervise scripts for service
  service_name   - name of service with full path
                   e.g. (/service/qmail-smtpd.25)
                   (give multiple services enclosed in double quotes)
                   "/service/qmail-smtpd.25 /service/qmail-imapd.143"
                   service_name can be "all" to act on all services
  run-file-only  - Recreate run files but not variables
  force          - Recreate service even if it has norefreshsvc flag
  NOTE: if the file .norefreshsvc is present in the variable or the config
  directory, refresh is skipped

--autorefresh="0|1 service_name"

  Disable/Enable auto refresh of supervise scripts for service
  0              - Disable autorefresh (create .norefreshsvc in variables directory)
  1              - Enable  autorefresh (delete .norefreshsvc in variables directory)
  service_name   - name of service with full path
                   e.g. (/service/qmail-smtpd.25)
                   service_name can be "all" to act on all services

--enable-service name1 name2 ..

  Add a service to be started at system boot. The unit file for the service should exist
  name1 name2 .. - name of a service or list of services to be added
                   This should be a SYSV style service, systemd, event.d unit file

--disable-service name1 name2 ..

  Remove a service to be started at system boot. The unit file for the service should exist
  name1 name2 .. - name of a service or list of services to be removed
                   This should be a SYSV style service, systemd, event.d unit file

--config=add-boot|rm-boot|users|rmusers|inittab|cert
  [--postmaster=user[@domain]]
  [--common_name=CN]
  [--validity_days=days]
  [--capath=ca_path_dir]
  [--certdir=certdir]
  [--update-certs]

  add-boot       - Add startup scripts for IndiMail to get started during boot
  rm-boot        - Remove Startup scripts to prevent IndiMail to get started after boot
  users          - Create Internal System Users needed by svscan
  rmusers        - Delete Internal System Users needed by svscan
  inittab        - Install svscan started by configuration in /etc/inittab
  cert           - Generate SSL Certificate
  postmaster     - name of the user who will recieve bounces on the local host.
                   This can also be a remote user i.e. &postmaster@indimail.org
  common_name    - Common Name (CN) for server
  days           - Number of days for which the Certificate should be valid
  ca_path_dir    - Directory having CA certificate
  certdir        - Directory in which new certificates will be placed
  update-certs   - Update CERTDIR, CERTFILE and TLSCACHE for services using them

--check-certs=[full path of certificate]
  Check certificate given as argument or
  Check IndiMail Certificates in /etc/indimail/certs without any arguments

--set-variable=n --variable-value=v
  --servicedir=service_path
  --service-name=service_name
  [--force]

  Set a new variable for a supervise service
  n              - variable name
  v              - variable value
  service_path   - Path where supervise service will be installed
  service_name   - Service name
  force          - Overwrite variable if it exists

--modify-variable=n --variable-value=v
  --servicedir=service_path
  --service-name=service_name
  [--force]

  Modify an existing variable for a supervise service
  n              - variable name
  v              - variable value
  service_path   - Path where supervise service will be installed
  service_name   - Service name
  force          - Set the variable even if does not exist

--unset-variable=n
  --servicedir=service_path
  --service-name=service_name

  Unset any existing environment variable named 'n'
  n              - variable name
  service_name   - Service name

--remove-variable=n
  --servicedir=service_path
  --service-name=service_name

  Remove an existing variable for a supervise service
  n              - variable name
  service_path   - Path where supervise service will be installed
  service_name   - Service name

--restore-variables
  --servicedir=service_path
  --service-name=service_name

  Clean and Restore all variables to original state from
  servicedir/service_name/variables/.variables file
  service_path   - Path where supervise service will be installed
  service_name   - name of supervise service without path
                   e.g. (qmail-smtpd.25)

--import-variables=file
  --servicedir=service_path
  --service-name=service_name
  [--force] [--silent]

  Import new environment variables from a file having one more multiple
  key=value pairs
  file           - File from which to import key=value environment variables
  service_path   - Path where supervise service will be installed
  service_name   - name of supervise service without path
                   e.g. (qmail-smtpd.25)
  force          - Set the variable if variable already exists
  silent         - be less verbose

--export-variables=file
  --servicedir=service_path
  --service-name=service_name
  [--force]

  Export existing environment variables to a file
  file           - File in which to save key=value environment variables
  service_path   - Path where supervise service will be installed
  service_name   - name of supervise service without path
                   e.g. (qmail-smtpd.25)
  force          - overwrite service_path/service_name/variables/.variables

--save-variables
  --servicedir=service_path

  Export variables for all service in /service and
  /etc/indimail/control/defaultqueue
  service_path   - Path where supervise service will be installed

--restore-all-variables
  --servicedir=service_path

  Restore all variables to orignal state for all service in
  /service and /etc/indimail/control/defaultqueue
  service_path   - Path where supervise service will be installed

--print-variables
  --servicedir=service_path
  --service-name=service_name | --envdir=dir

  Print environment variables for a service
  service_path   - Path where supervise service will be installed
  service_name   - name of supervise service without path
                   e.g. (qmail-smtpd.25)
  dir            - Environment variables directory

--print-all-variables
  --servicedir=service_path

  Print environment variables all services
  service_path   - Path where supervise service will be installed

--dumpconfig --servicedir=service_path --cntrldir=cntrl_path

  Dumps all service configuration for Supervise Scripts, control files and software information
  service_path - Path where supervise service will be installed
  cntrl_path   - Path where Qmail control files are stored

--help

  display this help and exit

--version

  output version information
EOF
exit $1
}

dump_run_header()
{
echo "#!/bin/sh"
echo "$RCSID"
echo "# generated run script for $host at `date`"
echo "# by the below command"
echo "# $prog_args"
echo ""
}

dump_log_header()
{
if [ $# -ne 1 ] ; then
	echo "Usage: dump_log_header log_sub_dir" 1>&2
	exit 1
fi
echo "#!/bin/sh"
echo "$RCSID"
echo "# generated log script for $host at `date`"
echo "# by the below command"
echo "# $prog_args"
echo ""
echo "exec $prefix/bin/setuidgid qmaill \\"
echo "  $prefix/sbin/multilog t $LOGDIR/$1"
}

link_with_global()
{
if [ $# -ne 1 ] ; then
	echo "USAGE: link_with_global conf_dir" 1>&2
	return 1
fi
conf_dir=$1
if [ $nooverwrite -eq 1 -a -d $conf_dir ] ; then
	return 0
fi
if [ ! -d "$DESTDIR"$sysconfdir/control/global_vars ] ; then
	mkdir -p "$DESTDIR"$sysconfdir/control/global_vars
	/usr/bin/getent group  qmail  > /dev/null && \
		$chown root:qmail "$DESTDIR"$sysconfdir/control/global_vars || \
		$chown root:0 "$DESTDIR"$sysconfdir/control/global_vars
	/bin/chmod 755 "$DESTDIR"$sysconfdir/control/global_vars
fi
if [ ! -f $conf_dir/.envdir -a ! -d $conf_dir/.envdir -a ! -L $conf_dir/.envdir ] ; then
	echo $sysconfdir/control/global_vars > $conf_dir/.envdir
fi
if [ ! -x "$DESTDIR"$prefix/sbin/qmail-send ] ; then
	return 0
fi
if [ $usefsync -eq 1 -o $usefdatasync -eq 1 ] ; then
	echo 1 > "$DESTDIR"$sysconfdir/control/global_vars/USE_FDATASYNC
else
	> "$DESTDIR"$sysconfdir/control/global_vars/USE_FSYNC
	> "$DESTDIR"$sysconfdir/control/global_vars/USE_FDATASYNC
fi
if [ $usesyncdir -eq 1 ] ; then
	SYSTEM=$(uname -s)
	case "$SYSTEM" in
		Linux)
		echo 1 > "$DESTDIR"$sysconfdir/control/global_vars/USE_SYNCDIR
		;;
		*)
		> "$DESTDIR"$sysconfdir/control/global_vars/USE_SYNCDIR
		;;
	esac
else
	> "$DESTDIR"$sysconfdir/control/global_vars/USE_SYNCDIR
fi
}

create_svscan()
{
if [ $# -lt 1 ] ; then
	echo "USAGE: create_svscan supervise_dir [initcmd]" 1>&2
	return 1
fi
SERVICEDIR=$1
if [ $# -eq 2 ] ; then
	init_cmd=$2
else
	init_cmd=""
fi
if [ $nooverwrite -eq 1 -a -d "$DESTDIR"$SERVICEDIR/.svscan/log ] ; then
	return 0
fi
if [ $mount_resolvconf -eq 1 ] ; then
	if [ ! -x /usr/bin/unshare ] ; then
		echo "/usr/bin/unshare: No access or unshare command missing" 1>&2
		return 1
	fi
	if [ ! -x "$DESTDIR"$SERVICEDIR/dnscache/run ] ; then
		echo "djb dnscache service is required for --resolvconf" 1>&2
		return 1
	fi
fi
# Setup variables INITCMD, SCANINTERVAL, SCANLOG, UNSHARE
conf_dir="$DESTDIR"$SERVICEDIR/.svscan/variables
if [ $run_file_only -eq 1 ] ; then
	if [ -d $conf_dir ] ; then
		/bin/mv $conf_dir "$conf_dir".bak
	fi
fi
/bin/mkdir -p $conf_dir
/bin/chmod 500 $conf_dir
link_with_global $conf_dir
echo "$prog_args" > $conf_dir/.options
if [ -z $init_cmd ] ; then
	echo           > $conf_dir/INITCMD
else
	echo $init_cmd > $conf_dir/INITCMD
fi
echo "/usr/bin:/bin:/usr/local/bin:/usr/sbin:/sbin:/usr/local/sbin" > $conf_dir/PATH
if [ " $scan_interval" = " " ] ; then
	echo           "300"  > $conf_dir/SCANINTERVAL
else
	echo "$scan_interval" > $conf_dir/SCANINTERVAL
fi
echo > $conf_dir/SCANLOG
if [ -x /usr/bin/unshare -a $use_unshare -eq 1 ] ; then
	echo > $conf_dir/UNSHARE
else
	> $conf_dir/UNSHARE
fi

if [ -x /usr/bin/mount ] ; then
	mount=/usr/bin/mount
elif [ -x /bin/mount ] ; then
	mount=/bin/mount
elif [ -x /sbin/mount ] ; then
	mount=/sbin/mount
else
	echo "mount command not found" 1>&2
	return 1
fi
if [ -x /usr/bin/umount ] ; then
	umount=/usr/bin/umount
elif [ -x /bin/umount ] ; then
	umount=/bin/umount
elif [ -x /sbin/umount ] ; then
	umount=/sbin/umount
else
	echo "umount command not found" 1>&2
	return 1
fi
echo 1 > $conf_dir/AUTOSCAN
/bin/mkdir -p "$DESTDIR"$SERVICEDIR/.svscan/log
/bin/mkdir -p "$DESTDIR"$sysconfdir
if [ $mount_resolvconf -eq 1 ] ; then
	# svscan run script
	(
	dump_run_header
	echo "echo svscan \$PPID initialization PID \$\$"
	echo "exec 2>&1"
	echo "if [ -s $SERVICEDIR/variables/UNSHARE -a -f $sysconfdir/resolv.conf ] ; then"
	echo "  /usr/bin/mount --bind $sysconfdir/resolv.conf /etc/resolv.conf"
	echo "  /usr/bin/mount -l"
	echo "fi"
	echo ""
	echo "echo \"Environment Variable List\""
	echo "env"
	) > "$DESTDIR"$SERVICEDIR/.svscan/run
	if [ ! -f "$DESTDIR"$sysconfdir/resolv.conf -o $force -eq 1 ] ; then
		hostname=$([ -n "$HOSTNAME" ] && echo "$HOSTNAME" || uname -n)
		(
		echo "# $prog_args"
		echo "# generated at `date`"
		echo "search $hostname"
		echo "nameserver 127.0.0.1"
		) > "$DESTDIR"$sysconfdir/resolv.conf
	fi
	/bin/chmod +x "$DESTDIR"$SERVICEDIR/.svscan/run
else
	if [ -x "$DESTDIR"$SERVICEDIR/.svscan/run ] ; then
		/bin/chmod -x "$DESTDIR"$SERVICEDIR/.svscan/run
	fi
fi

(
dump_run_header
echo "exec 2>&1"
if [ $mount_resolvconf -eq 1 ] ; then
	echo "if [ -s $SERVICEDIR/variables/UNSHARE -a -f $sysconfdir/resolv.conf ] ; then"
	echo "  /usr/bin/umount /etc/resolv.conf"
	echo "fi"
fi
echo "$prefix/bin/svc -dx $SERVICEDIR/*"
) > "$DESTDIR"$SERVICEDIR/.svscan/shutdown
/bin/chmod +x "$DESTDIR"$SERVICEDIR/.svscan/shutdown

if [ ! -d $LOGDIR ] ; then
	/bin/mkdir -p $LOGDIR
	$chown qmaill:nofiles $LOGDIR
fi
# svscan log script
dump_log_header svscan > "$DESTDIR"$SERVICEDIR/.svscan/log/run
/bin/chmod +x "$DESTDIR"$SERVICEDIR/.svscan/log/run

if [ $run_file_only -eq 1 ] ; then
	if [ -d "$conf_dir".bak ] ; then
		/bin/rm -rf $conf_dir
		/bin/mv "$conf_dir".bak $conf_dir
	fi
fi

# resolvconf script using inotify
if [ $mount_resolvconf -eq 1 -a \
		-x /usr/bin/unshare -a \
		-x "$DESTDIR"$SERVICEDIR/dnscache/run -a \
		-x "$DESTDIR"$prefix/bin/inotify ] ; then
	conf_dir="$DESTDIR"$SERVICEDIR/resolvconf/variables
	if [ $run_file_only -eq 1 ] ; then
		if [ -d $conf_dir ] ; then
			/bin/mv $conf_dir "$conf_dir".bak
		fi
	fi
	/bin/mkdir -p "$DESTDIR"$SERVICEDIR/resolvconf/log
	if [ $down_state -eq 1 ] ; then
		$TOUCH "$DESTDIR"$SERVICEDIR/resolvconf/down
	fi
	/bin/mkdir -p $conf_dir
	/bin/chmod 500 $conf_dir
	link_with_global $conf_dir
	echo "$prog_args" > $conf_dir/.options
	# resolvconf run script
	(
	dump_run_header
	echo "trap clean_up 1 2 15"
	echo ""
	echo "function clean_up"
	echo "{"
	echo "	echo \"shutting down\""
	echo "	pkill -P \$(jobs -p) inotify"
	echo "	exit"
	echo "}"
	echo ""
	echo "exec 2>&1"
	echo "file=\$(realpath /etc/resolv.conf)"
	echo "dir=\$(dirname \$file)"
	echo "echo \"starting with resolv_conf_dir=\$dir\""
	echo "/bin/cat /etc/resolv.conf"
	echo "exec 2>&1"
	echo "("
	echo "/usr/bin/inotify -n \$dir | while read line"
	echo "do"
	echo "	set \$line"
	echo "	if [ \" \$1\" != \" file\" ] ; then"
	echo "		continue"
	echo "	fi"
	echo "	file=\$2"
	echo "	event=\$3"
	echo "	if [ \" \$file\" != \" resolv.conf\" ] ; then"
	echo "		continue"
	echo "	fi"
	echo "	if [ \" \$event\" != \" closed\" ] ; then"
	echo "		continue"
	echo "	fi"
	echo "	list=\`grep nameserver /etc/resolv.conf\` > /dev/null"
	echo "	if [ \$? -eq 0 ] ; then"
	echo "		echo \$list"
	echo "		echo \"$umount /etc/resolv.conf\""
	echo "		$umount /etc/resolv.conf"
	echo "		echo \"$mount --bind $sysconfdir/resolv.conf /etc/resolv.conf\""
	echo "		$mount --bind $sysconfdir/resolv.conf /etc/resolv.conf"
	echo "	fi"
	echo "done"
	echo ") &"
	echo "wait"
	) > "$DESTDIR"$SERVICEDIR/resolvconf/run
	/bin/chmod +x "$DESTDIR"$SERVICEDIR/resolvconf/run

	# resolvconf log script
	dump_log_header resolvconf > "$DESTDIR"$SERVICEDIR/resolvconf/log/run
	/bin/chmod +x "$DESTDIR"$SERVICEDIR/resolvconf/log/run
fi

if [ $run_file_only -eq 1 ] ; then
	if [ -d "$conf_dir".bak ] ; then
		/bin/rm -rf $conf_dir
		/bin/mv "$conf_dir".bak $conf_dir
	fi
fi
}

rmsvc()
{
if [ $# -lt 1 ] ; then
	echo "rmsvc service_with_full_path" 1>&2
	return 1
fi
if [ -d /run ] ; then
	rundir=/run/svscan
elif [ -d /var/run ] ; then
	rundir=/var/run/svscan
fi
for i in $*
do
	if [ ! -d $i ] ; then
		echo "$i: No such file or directory" 1>&2
		continue
	fi
	dir=`dirname $i`
	svcname=`basename $i`
	first_char=`echo ${svcname} | cut -c1`
	if [ " $first_char" = " ." ] ; then
		echo "skipping $i that starts with ." 1>&2
		continue
	fi
	if [ -n "$rundir" ] ; then
		if [ ! -p $rundir/${svcname}/supervise/control ] ; then
			echo "$i/supervise not a supervise directory" 1>&2
			continue
		fi
	else
		if [ ! -p $i/supervise/control ] ; then
			echo "$i/supervise not a supervise directory" 1>&2
			continue
		fi
	fi
	/bin/mv $i $dir/"."${svcname}
	if [ $? -ne 0 ] ; then
		continue
	fi
	if [ -n "$rundir" ] ; then
		if [ -d $rundir/${svcname} -a ! -d $rundir/"."${svcname} ] ; then
			/bin/mv $rundir/${svcname} $rundir/"."${svcname}
			if [ $? -ne 0 ] ; then
				continue
			fi
		fi
		dir=$rundir
	fi
	#
	# prepend a . to the directory so that svscan will skip this directory
	#
	echo "Removed Service ${svcname}"
	"$DESTDIR"$prefix/bin/svc -dx $dir/"."${svcname}
	if [ -d $dir/"."${svcname}/log ] ; then
		echo "Removed Service ${svcname}/log"
		"$DESTDIR"$prefix/bin/svc -dx $dir/"."${svcname}/log
	fi
done
}

ensvc()
{
if [ $# -lt 1 ] ; then
	echo "ensvc service_with_full_path" 1>&2
	return 1
fi
if [ -d /run ] ; then
	rundir=/run/svscan
elif [ -d /var/run ] ; then
	rundir=/var/run/svscan
fi
for i in $*
do
	if [ ! -d $i ] ; then
		echo "$i: No such file or directory" 1>&2
		continue
	fi
	dir=`dirname $i`
	svcname=`basename $i`
	first_char=`echo ${svcname} | cut -c1`
	if [ " $first_char" = " ." ] ; then
		second_char=`echo ${svcname} | cut -c2`
		if [ " $second_char" = " ." -o -z "$second_char" ] ; then
			echo "skipping $i" 1>&2
			continue
		fi
		svcname=`echo ${svcname} | cut -c2-`
		if [ -d $dir/${svcname} ] ; then
			echo "$dir/${svcname} exists"
			continue;
		fi
		/bin/mv $i $dir/${svcname}
		if [ $? -ne 0 ] ; then
			continue
		fi
		if [ -n "$rundir" ] ; then
			/bin/rm -rf $rundir/"."${svcname}
		fi
		echo "Enabled Service ${svcname}" 
	else
		echo "Service $i is not disabled (should have a '.' as the first char in ${svcname})" 1>&2
	fi
done
sleep 5
for i in $*
do
	dir=`dirname $i`
	svcname=`basename $i`
	first_char=`echo ${svcname} | cut -c1`
	if [ " $first_char" = " ." ] ; then
		second_char=`echo ${svcname} | cut -c2`
		if [ " $second_char" = " ." -o -z "$second_char" ] ; then
			echo "skipping $i" 1>&2
			continue
		fi
		svcname=`echo ${svcname} | cut -c2-`
		"$DESTDIR"$prefix/bin/svstat $dir/$svcname
		if [ -d $dir/${svcname}/log ] ; then
			"$DESTDIR"$prefix/bin/svstat $dir/${svcname}/log
		fi
	fi
done
}

refreshsvc()
{
if [ $# -lt 1 ] ; then
	echo "refreshsvc service_with_full_path" 1>&2
	return 1
fi
if [ " $1" = " all" ] ; then
	for j in `/bin/ls "$DESTDIR"$servicedir/*/variables/.options "$DESTDIR"$servicedir/.svscan/variables/.options 2>/dev/null`
	do
		# remove last 19 char to get the directory+service_name
		i=`echo $j|sed 's/.\{19\}$//'`
		svcname=`basename $i`
		if [ ! -s $i/variables/.options -a ! -s $i/.options ] ; then
			echo "$i/variables/.options or $i/.options missing" 1>&2
			continue
		fi
		if [ -f $i/variables/.norefreshsvc -a $force -eq 0 ] ; then
			if [ $silent -eq 0 ] ; then
				echo "Skip Refreshing service $svcname"
			fi
		else
			if [ $silent -eq 0 ] ; then
				echo "Refreshing service $svcname command `/bin/cat $i/variables/.options`"
			fi
			sh $i/variables/.options
		fi
	done
	if [ -f "$DESTDIR"$sysconfdir/control/defaultqueue/.norefreshsvc -a $force -eq 0 ] ; then
		if [ $silent -eq 0 ] ; then
			echo "Skip Refreshing config defaultqueue"
		fi
	else
		if [ $silent -eq 0 ] ; then
			echo "Refreshing config defaultqueue command `/bin/cat "$DESTDIR"$sysconfdir/control/defaultqueue/.options`"
		fi
		sh "$DESTDIR"$sysconfdir/control/defaultqueue/.options
	fi
else
	for i in $*
	do
		if [ ! -d "$DESTDIR"$i ] ; then
			echo "$i: No such file or directory" 1>&2
			continue
		fi
		svcname=`basename $i`
		if [ ! -s "$DESTDIR"$i/variables/.options -a ! -s "$DESTDIR"$i/.options ] ; then
			echo "$i/variables/.options or $i/.options missing" 1>&2
			continue
		fi
		if [ -f "$DESTDIR"$i/variables/.norefreshsvc -o -f "$DESTDIR"$i/.norefreshsvc ] ; then
			if [ $force -eq 0 ] ; then
				if [ $silent -eq 0 ] ; then
					echo "Skip Refreshing service/config $svcname"
				fi
				continue
			fi
		fi
		if [ -f "$DESTDIR"$i/variables/.options ] ; then
			if [ $silent -eq 0 ] ; then
				echo "Refreshing service $svcname command `/bin/cat "$DESTDIR"$i/variables/.options`"
			fi
			sh "$DESTDIR"$i/variables/.options
		elif [ -f "$DESTDIR"$i/.options ] ; then
			if [ $silent -eq 0 ] ; then
				echo "Refreshing config $svcname command `/bin/cat "$DESTDIR"$i/.options`"
			fi
			sh "$DESTDIR"$i/.options
		fi
	done
fi
}

autorefresh()
{
if [ $# -lt 2 ] ; then
	echo "autorefresh=0|1 service_with_full_path" 1>&2
	return 1
fi
svc_opt=$1
shift
if [ " $1" = " all" ] ; then
	for j in `/bin/ls "$DESTDIR"$servicedir/*/variables/.options "$DESTDIR"$servicedir/.svscan/variables/.options 2>/dev/null`
	do
		# remove last 19 char to get the directory+service_name
		i=`echo $j|sed 's/.\{19\}$//'`
		if [ ! -s $i/variables/.options -a ! -s $i/.options ] ; then
			echo "$i/variables/.options or $i/.options missing" 1>&2
			continue
		fi
		if [ $svc_opt -eq 1 ] ; then
			if [ $silent -eq 0 ] ; then
				echo "Enabling  auto refresh for $i"
			fi
			/bin/rm -f $i/variables/.norefreshsvc
		else
			if [ $silent -eq 0 ] ; then
				echo "Disabling auto refresh for $i"
			fi
			touch $i/variables/.norefreshsvc
		fi
	done
	if [ $svc_opt -eq 1 ] ; then
		if [ $silent -eq 0 ] ; then
			echo "Enabling  auto refresh for $sysconfdir/control/defaultqueue"
		fi
		/bin/rm -f "$DESTDIR"$sysconfdir/control/defaultqueue/.norefreshsvc
	else
		if [ $silent -eq 0 ] ; then
			echo "Disabling auto refresh for $sysconfdir/control/defaultqueue"
		fi
		touch "$DESTDIR"$sysconfdir/control/defaultqueue/.norefreshsvc
	fi
else
	for i in $*
	do
		if [ ! -d "$DESTDIR"$i ] ; then
			echo "$i: No such file or directory" 1>&2
			continue
		fi
		if [ ! -s "$DESTDIR"$i/variables/.options -a ! -s "$DESTDIR"$i/.options ] ; then
			echo "$i/variables/.options or $i/.options missing" 1>&2
			continue
		fi
		if [ $svc_opt -eq 1 ] ; then
			if [ $silent -eq 0 ] ; then
				echo "Enabling  auto refresh for $1"
			fi
			if [ -d $i/variables ] ; then
				/bin/rm -f "$DESTDIR"$i/variables/.norefreshsvc
			else
				/bin/rm -f "$DESTDIR"$i/.norefreshsvc
			fi
		else
			if [ $silent -eq 0 ] ; then
				echo "Disabling auto refresh for $i"
			fi
			if [ -d "$DESTDIR"$i/variables ] ; then
				touch "$DESTDIR"$i/variables/.norefreshsvc
			else
				touch "$DESTDIR"$i/.norefreshsvc
			fi
		fi
	done
fi
}

create_startup()
{
	case "$host" in
		*-*-darwin*)
		if [ -n "$DESTDIR" ] ; then
			/bin/mkdir -p "$DESTDIR"/etc
		fi
		if [ ! -f /etc/synthetic.conf ] ; then
			if [ $silent -eq 0 ] ; then
				echo "Creating /service in /etc/synthetic.conf"
			fi
			printf "service\t/System/Volumes/Data/etc/indimail/sv\n" > /etc/synthetic.conf
		else
			grep "^service" /etc/synthetic.conf >/dev/null
			if [ $? -ne 0 ] ; then
				if [ $silent -eq 0 ] ; then
					echo "Creating /service in /etc/synthetic.conf"
				fi
				if [ -z "$DESTDIR" ] ; then
					printf "service\t/System/Volumes/Data/etc/indimail/sv\n" >> /etc/synthetic.conf
				else
				(
					printf "service\t/System/Volumes/Data/etc/indimail/sv\n"
					cat /etc/synthetic.conf
				) > "$DESTDIR"/etc/synthetic.conf
				fi
			else
				echo "/service exists in /etc/synthetic.conf" 1>&2
			fi
		fi
		;;
		*)
		if [ ! -d /service -a ! -L /service ] ; then
			if [ -d /run ] ; then
				ln -s /run/svscan /service
			elif [ -d /var/run ] ; then
				ln -s /var/run/svscan /service
			elif [ "$servicedir" != "/service" ] ; then
				ln -s $servicedir /service
			fi
		fi
		;;
	esac
	if [ -x "$DESTDIR"$prefix/sbin/initsvc ] ; then
		"$DESTDIR"$prefix/sbin/initsvc -status
	else
		if [ -x /bin/systemctl -a -d /lib/systemd/system ] ; then
			cmp -s "$DESTDIR"$shareddir/boot/systemd /lib/systemd/system/svscan.service >/dev/null 2>&1
			if [ $? -ne 0 ] ; then
				if [ $silent -eq 0 ] ; then
					echo "svscan startup enabled in systemd /lib/systemd/system/svscan.service"
				fi
				/bin/cp "$DESTDIR"$shareddir/boot/systemd /lib/systemd/system/svscan.service
				/bin/systemctl daemon-reload && echo "installed new svscan service"
			fi
		elif [ -x /bin/systemctl -a -d /usr/lib/systemd/system ] ; then
			cmp -s "$DESTDIR"$shareddir/boot/systemd /usr/lib/systemd/system/svscan.service >/dev/null 2>&1
			if [ $? -ne 0 ] ; then
				if [ $silent -eq 0 ] ; then
					echo "svscan startup enabled in systemd /usr/lib/systemd/system/svscan.service"
				fi
				/bin/cp "$DESTDIR"$shareddir/boot/systemd /usr/lib/systemd/system/svscan.service
				/bin/systemctl daemon-reload && echo "installed new svscan service"
			fi
		elif [ -f /sbin/initctl -a -d /etc/init ] ; then
			cmp -s "$DESTDIR"$shareddir/boot/upstart /etc/init/svscan.conf >/dev/null 2>&1
			if [ $? -ne 0 ] ; then
				if [ $silent -eq 0 ] ; then
					echo "svscan startup enabled in /etc/init/svscan.conf"
				fi
				/bin/cp "$DESTDIR"$shareddir/boot/upstart /etc/init/svscan.conf
			fi
		elif [ -d /etc/event.d ] ; then
			cmp -s "$DESTDIR"$shareddir/boot/upstart /etc/event.d/upstart >/dev/null 2>&1
			if [ $? -ne 0 ] ; then
				if [ $silent -eq 0 ] ; then
					echo "svscan startup enabled in /etc/event.d/upstart"
				fi
				/bin/cp "$DESTDIR"$shareddir/boot/upstart /etc/event.d
			fi
		elif [ -d /etc/rc.d -a -f /etc/rc.subr ] ; then
			cmp -s "$DESTDIR"$shareddir/boot/svscan $prefix/etc/rc.d/svscan >/dev/null 2>&1
			if [ $? -ne 0 ] ; then
				if [ $silent -eq 0 ] ; then
					echo "svscan startup enabled in rc $prefix/etc/rc.d/svscan"
				fi
				/bin/cp "$DESTDIR"$shareddir/boot/svscan $prefix/etc/rc.d/svscan
				/bin/chmod 755 $prefix/etc/rc.d/svscan
				service svscan enable
			fi
		elif [ -d /Library/LaunchDaemons ] ; then
			cmp -s "$DESTDIR"$shareddir/boot/svscan.plist /Library/LaunchDaemons/org.indimail.svscan.plist >/dev/null 2>&1
			if [ $? -ne 0 ] ; then
				if [ $silent -eq 0 ] ; then
					echo "svscan startup enabled in /Library/LaunchDaemons/org.indimail.svscan.plist"
				fi
				/bin/cp "$DESTDIR"$shareddir/boot/svscan.plist /Library/LaunchDaemons/org.indimail.svscan.plist
			fi
		elif [ -f /sbin/openrc-run -a -d /etc/init.d ] ; then
			cmp -s "$DESTDIR"$shareddir/boot/openrc /etc/init.d/svscan >/dev/null 2>&1
			if [ $? -ne 0 ] ; then
				if [ $silent -eq 0 ] ; then
					echo "svscan startup enabled in rc /etc/init.d/svscan"
				fi
				/bin/cp "$DESTDIR"$shareddir/boot/openrc /etc/init.d/svscan
				/bin/chmod 755 /etc/init.d/svscan
				service svscan enable
			fi
		elif [ -f /etc/inittab ] ; then
			grep ".*:.*:respawn:.*svscanboot" /etc/inittab >/dev/null
			if [ $? -eq 0 ] ; then
				grep ".*:.*:respawn:.*svscanboot" /etc/inittab |grep respawn >/dev/null
				if [ $? -eq 0 ] ; then
					if [ $silent -eq 0 ] ; then
						echo "svscan startup enabled in /etc/inittab"
					fi
				else
					echo "svscan startup configured in /etc/inittab but not enabled"
				fi
			fi
		fi
	fi
	if [ ! -f /sbin/openrc-run -a -d /etc/init.d ] ; then
		cmp -s "$DESTDIR"$prefix/bin/qmailctl /etc/init.d/svscan >/dev/null 2>&1
		if [ $? -ne 0 ] ; then
			/bin/cp "$DESTDIR"$prefix/bin/qmailctl /etc/init.d/svscan
		fi
	fi
	if [ -f /etc/init.d/svscan ] ; then
		if [ -f /sbin/chkconfig ] ; then
			if [ -f /etc/debian_version ] ; then
				/sbin/chkconfig --add svscan 2>/dev/null
			else
				/sbin/chkconfig --add svscan
			fi
		elif [ -f /usr/sbin/chkconfig ] ; then
			/usr/sbin/chkconfig --add svscan
		elif [ -f /usr/sbin/update-rc.d ] ; then
			/usr/sbin/update-rc.d svscan start 14 2 3 4 5 . stop 91 0 1 6 .
		fi
	fi
}

remove_startup()
{
	echo "Giving svscan exactly 5 seconds to exit nicely" 1>&2
	if [ -f "$DESTDIR"$prefix/sbin/initsvc ] ; then
		"$DESTDIR"$prefix/sbin/initsvc -off
	fi
	if [ -f /lib/systemd/system/svscan.service -a -x /bin/systemctl ] ; then
		/bin/systemctl stop svscan
		/bin/systemctl disable svscan.service
		/bin/rm -f /lib/systemd/system/svscan.service
		/bin/systemctl daemon-reload && echo "removed svscan service"
	elif [ -f /usr/lib/systemd/system/svscan.service -a -x /bin/systemctl ] ; then
		/bin/systemctl stop svscan
		/bin/systemctl disable svscan.service
		/bin/rm -f /usr/lib/systemd/system/svscan
		/bin/systemctl daemon-reload && echo "removed svscan service"
	elif [ -f /etc/init/svscan.conf ] ; then
		/sbin/initctl emit qmailstop > /dev/null
		/bin/rm -f /etc/event.d/svscan
	elif [ -f /etc/event.d/svscan ] ; then
		/sbin/initctl emit qmailstop > /dev/null
		/bin/rm -f /etc/event.d/svscan
	elif [ -f /sbin/openrc-run ] ; then
		service svscan stop
		if [ -f /etc/init.d/svscan ] ; then
			service svscan disable
		fi
		/bin/rm -f /etc/init.d/svscan
	elif [ -f /etc/inittab ] ; then
		service svscan stop
		sed -i '/svscan/d' /etc/inittab
		kill -1 1
	elif [ -d /etc/rc.d -a -f /etc/rc.subr ] ; then
		service svscan stop
		if [ -f $prefix/etc/rc.d/svscan ] ; then
			service svscan disable && service svscan delete
			/bin/rm -f $prefix/etc/rc.d/svscan
		fi
	fi
	if [ -f /etc/init.d/svscan ] ; then
		if [ -f /sbin/chkconfig ] ; then
			if [ -f /etc/debian_version ] ; then
				/sbin/chkconfig --del svscan 2>/dev/null
			else
				/sbin/chkconfig --del svscan
			fi
		elif [ -f /usr/sbin/chkconfig ] ; then
			/usr/sbin/chkconfig --del svscan 2>/dev/null
		elif [ -f /usr/sbin/update-rc.d ] ; then
			/usr/sbin/update-rc.d -f svscan remove
		fi
		/bin/rm -f /etc/init.d/svscan
	fi
}

check_update_if_diff()
{
	if [ ! -s $1 -o ! -f $1 ] ; then
		update=1
	else
		update=0
		val=`cat $1 2>/dev/null`
	fi
	if [ $update -eq 1 -o ! " $val" = " $2" ] ; then
		if [ $silent -eq 0 ] ; then
			echo "updating $1 with $2"
		fi
		echo $2 > $1
		return 1
	else
		return 0
	fi
}

import_variables()
{
if [ $# -ne 6 ] ; then
	echo "usage: import_variables dir envfile restore_flag owner group mode" 1>&2
	exit 1
fi
dir=$1
env_file=$2
restore_flag=$3
owner=$4
group=$5
mode=$6
if [ $silent -eq 0 ] ; then
	if [ $restore_flag -eq 1 ] ; then
		printf "Restoring %-40s from %s\n" $dir $env_file
		old=$silent
		silent=1
	else
		printf "importing %-40s from %s\n" $dir $env_file
	fi
fi
sed -e 's{^[ \t]*#.*{{g ; s{^[ \t]*{{g ; s{#.*{{ ;  /^$/d' $env_file | while read line
do
	if [ -z "$line" ] ; then
		continue
	fi
	file=`echo $line | cut -d= -f1`
	value=`echo $line | cut -d= -f2- | tr -d \"`
	# when importing variables
	if [ $restore_flag -eq 0 -a $force -eq 0 -a -f $dir/$file ] ; then
		if [ $silent -eq 0 ] ; then
			echo "importing variables without --force. not replacing variable $file" 1>&2
		fi
		continue
	fi
	if [ -z "$value" ] ; then
		value=`echo $line | cut -d= -f2-`
		if [ -z "$value" ] ; then
			# variable=
			# unset/remove variable
			if [ -s $dir/$file -o ! -f $dir/$file ] ; then
				if [ $silent -eq 0 ] ; then
					echo "unset env variable $file"
				fi
				> $dir/$file
			fi
		else
			# variable=""
			# set variable with empty value
			value=`echo $value | tr -d \"`
			check_update_if_diff $dir/$file "$value"
			if [ $? -ne 0 -a $silent -eq 0 ] ; then
				echo "set env variable $file=[$value]"
			fi
		fi
	else
		# variable="some value"
		# set variable=$value
		check_update_if_diff $dir/$file "$value"
		if [ $? -ne 0 -a $silent -eq 0 ] ; then
			echo "set env variable $file=[$value]"
		fi
	fi
	if [ -n "$mode" ] ; then
		/bin/chmod $mode $dir/$file
	fi
	if [ -n "$owner" -a -n "$group" ] ; then
		$chown $owner:$group $dir/$file
	elif [ -n "$owner" ] ; then
		$chown $owner $dir/$file
	fi
done
if [ $restore_flag -eq 1 ] ; then
	silent=$old
fi

# remove variables not originally present
# This will restore variables to original state
if [ $restore_flag -eq 1 ] ; then
	out=`mktemp -dt svctXXXXXXXXXXX`
	if [ $? -ne 0 ] ; then
		echo "unable to create temp dir" 1>&2
		return 1
	fi
	cat $env_file | while read line
	do
		file=`echo $line | cut -d= -f1`
		touch $out/$file
	done
	for j in `/bin/ls $dir`
	do
		if [ ! -f $out/$j ] ; then
			/bin/rm -f $dir/$j
		fi
	done
	/bin/rm -rf $out
fi
return 0
}

export_variables()
{
if [ $# -ne 5 ] ; then
	echo "usage: export_variables($#) dir envfile owner group mode" 1>&2
	exit 1
fi
dir=$1
file=$2
owner=$3
group=$4
mode=$5
if [ ! -d $dir ] ; then
	echo "$dir: No such file or directory" 1>&2
	exit 1
fi
if [ $? -ne 0 ] ; then
	echo "$dir: unable to chdir" 1>&2
	exit 1
fi
if [ $force -eq 0 -a -f $file ] ; then
	echo "$file exists and --force not specified" 1>&2
	return 1
fi
(
for i in `/bin/ls $dir`
do
	if [ -s $dir/$i ] ; then
		value=`cat $dir/$i`
		if [ -n "$value" ] ; then
			echo $i="$value"
		else
			echo $i=\"\"
		fi
	else
		echo "$i="
	fi
done
) > $file
if [ -s $file ] ; then
	/bin/chmod $mode $file
	$chown $owner:$group $file
else
	/bin/rm -f $file
fi
}

save_all_variables()
{
if [ -z "$owner" ] ; then
	owner=root
fi
if [ -z "$group" ] ; then
	group=0
fi
if [ -z $mode ] ; then
	mode=0640
fi
for i in `/bin/ls -d "$DESTDIR"$servicedir/*/variables "$DESTDIR"$servicedir/.svscan/variables 2>/dev/null`
do
	if [ $silent -eq 0 ] ; then
		printf "export %-35s %s %s %s\n" "`dirname $i`" $owner $group $mode
	fi
	export_variables $i $i/.variables $owner $group $mode 
done
dir="$DESTDIR"$sysconfdir/control/defaultqueue 
if [ -d $dir ] ; then
	if [ $silent -eq 0 ] ; then
		printf "export %-35s %s %s %s\n" $dir $owner $group $mode
	fi
	export_variables $dir $dir/.variables "indimail" "qmail" 0644
fi
}

restore_all_variables()
{
if [ -z "$owner" ] ; then
	owner=root
fi
if [ -z "$group" ] ; then
	group=0
fi
if [ -z $mode ] ; then
	mode=0640
fi
old=$force
force=1
for j in `/bin/ls "$DESTDIR"$servicedir/*/variables/.variables "$DESTDIR"$servicedir/.svscan/variables/.variables 2>/dev/nul`
do
	# remove last 21 char to get the directory+service_name
	i=`echo $j|sed 's/.\{21\}$//'`
	if [ ! -s $i/variables/.variables -a ! -s $i/.variables ] ; then
		echo "$i/variables/.variables or $i/.variables missing" 1>&2
		continue
	fi
	import_variables $i/variables $i/variables/.variables 1 $owner $group $mode
done
dir="$DESTDIR"$sysconfdir/control/defaultqueue
import_variables $dir $dir/.variables 1 "indimail" "qmail" 0644
force=$old
}

dump_config()
{
if [ $# -ne 2 ] ; then
	echo "USAGE: dump_config servicedir controldir" 1>&2
	return 1
fi
servicedir=$1
CONTROLDIR=$2
export CONTROLDIR
if [ ! -d $servicedir ] ; then
	echo "servicedir: No such file or directory" 1>&2
	return 1
fi
echo "Service Configuration ================================================"
echo Service Directory $servicedir
cd $servicedir
scount=1
for j in `/bin/ls -a $servicedir`
do
	if [ " $j" = " ." -o " $j" = " .." ] ; then
		continue
	fi
	printf "Service %05d %s\n" $scount $j
	scount=`expr $scount + 1`
	if [ -f $j/run ] ; then
		echo "Run File [$j/run]"
		/bin/cat $j/run
		/bin/echo -n "- EOF -----------------"
		printf "%-20s" "$j/run"
		echo "-----------------------"
		echo
	fi
	if [ -f $j/log/run ] ; then
		echo "Log Run File [$j/log/run]"
		/bin/cat $j/log/run
		/bin/echo -n "- EOF -----------------"
		printf "%-20s" "$j/log/run"
		echo "-----------------------"
		echo
	fi
	if [ -f $j/shutdown ] ; then
		echo "Shutdown File [$j/shutdown]"
		/bin/cat $j/shutdown
		/bin/echo -n "- EOF -----------------"
		printf "%-20s" "$j/shutdown"
		echo "-----------------------"
		echo
	fi
	if [ -d $j/variables ] ; then
		count=1
		for k in `ls $j/variables`
		do
			if [ $count -eq 1 ] ; then
				echo "Variables List"
			fi
			if [ -s $j/variables/$k ] ; then
				printf "%-3d %s\nValue:[" $count $k
				val=`/bin/cat $j/variables/$k`
				if [ " $val" = " " ] ; then
					/bin/echo -n "SET"
				else
					/bin/echo -n $val
				fi
				printf "]\n"
			else
				printf "%-3d %s\nValue:[UNSET]\n" $count $k
			fi
			count=`expr $count + 1`
			echo
		done
	fi
	echo
done
echo
echo "Control Configuration ================================================="
echo
"$DESTDIR"$prefix/bin/qmail-showctl
echo
echo "IndiMail Assign File:"
/bin/cat "$DESTDIR"$sysconfdir/users/assign
echo
}

enable_service()
{
	for i in $*
	do
		#
		# upstart/systemd
		#
		if [ -f /lib/systemd/system/$i.service -a -f /bin/systemctl ] ; then
			/bin/systemctl enable "$i".service
		elif [ -f /usr/lib/systemd/system/$i.service -a -f /bin/systemctl ] ; then
			/bin/systemctl enable "$i".service
		elif [ -f /Library/LaunchDaemons/org.indimail.svscan.plist ] ; then
			launchctl load -w /Library/LaunchDaemons/org.indimail.svscan.plist
		elif [ -f /sbin/initctl -a -f /etc/init/$i.override ] ; then
			/bin/rm -f /etc/init/$i.override
		elif [ -f /etc/event.d/$i.override ] ; then
			/bin/rm -f /etc/event.d/$i.override
		elif [ -f $QmailBinPrefix/etc/rc.d/svscan ] ; then
			service svscan enable
		fi
		#
		# traditional sys v
		#
		if [ -f /etc/init.d/$i ] ; then
			if [ -f /sbin/chkconfig ] ; then
				if [ -f /etc/debian_version ] ; then
					/sbin/chkconfig --add $i 2>/dev/null
				else
					/sbin/chkconfig --add $i
				fi
			elif [ -f /sbin/rc-update ] ; then
				/sbin/rc-update add $i
			elif [ -f /usr/sbin/update-rc.d ] ; then
				/usr/sbin/update-rc.d $i defaults
				/usr/sbin/update-rc.d $i enable
			fi
		fi
	done
}

disable_service()
{
	for i in $*
	do
		#
		# upstart/systemd
		#
		if [ -d /lib/systemd/system -a -f /bin/systemctl ] ; then
			/bin/systemctl stop "$i".service
			/bin/systemctl disable "$i".service
		elif [ -d /usr/lib/systemd/system -a -f /bin/systemctl ] ; then
			/bin/systemctl stop "$i".service
			/bin/systemctl disable "$i".service
		elif [ -f /Library/LaunchDaemons/org.indimail.svscan.plist ] ; then
			launchctl unload -w /Library/LaunchDaemons/org.indimail.svscan.plist 2>/dev/null
			launchctl remove /Library/LaunchDaemons/org.indimail.svscan.plist
		elif [ -f /sbin/initctl -a -d /etc/init ] ; then
			/sbin/initctl stop $i
			if [ -f /etc/init/$i.conf ] ; then
				echo "manual" > /etc/init/$i.override
			fi
		elif [ -d /etc/event.d ] ; then
			/sbin/initctl stop $i
			echo "manual" > /etc/event.d/$i.override
		elif [ -f $QmailBinPrefix/etc/rc.d/svscan ] ; then
			service svscan disable
		else
			/usr/sbin/service $i stop
		fi
		#
		# traditional sys v
		#
		if [ -f /etc/init.d/$i ] ; then
			/etc/init.d/$i stop
			if [ -f /sbin/chkconfig ] ; then
				if [ -f /etc/debian_version ] ; then
					/sbin/chkconfig --del $i 2>/dev/null
				else
					/sbin/chkconfig --del $i
				fi
			elif [ -f /sbin/rc-update ] ; then
				/sbin/rc-update del $i
			elif [ -f /usr/sbin/update-rc.d ] ; then
				/usr/sbin/update-rc.d -f $i disable
				/usr/sbin/update-rc.d -f $i remove
			fi
		fi
	done
}

macOSgroupadd()
{
	echo "groupadd $*"
	groupid=""
	while test $# -gt 1; do
		case "$1" in
		-g)
		groupid=$2
		for i in `dscl . -list /Groups PrimaryGroupID | awk '{print $2}'`
		do
			if [ $i -eq $groupid ] ; then
				echo "groupid $groupid not unique" 1>&2
				return 1
			fi
		done
		;;
		esac
		shift
	done
	/usr/bin/dscl . -list /Groups/$1 > /dev/null 2>&1
	if [ $? -eq 0 ] ; then
		echo "group $1 exists"
		return 1
	fi
	if [ -n "$groupid" ] ; then
		echo "dscl . -create /Groups/$1 PrimaryGroupID $groupid"
		/usr/bin/dscl . -create /Groups/$1 PrimaryGroupID $groupid
	else
		echo "dseditgroup -o create $1"
		/usr/sbin/dseditgroup -o create $1
	fi
	return $?
}

macOSuseradd()
{
	echo "useradd $*"
	userid=""
	group=""
	members=""
	homedir=""
	shell=""
	password=""
	create_home=1
	while test $# -gt 1; do
		case "$1" in
		-M)
		create_home=0
		;;
		-u)
		userid=$2
		for i in `dscl . -list /Users UniqueID | awk '{print $2}'`
		do
			if [ $i -eq $userid ] ; then
				echo "userid $userid not unique" 1>&2
				return 1
			fi
		done
		;;
		-g)
		group=$2
		dscl . -read /Groups/$group PrimaryGroupID >/dev/null 2>&1
		if [ $? -ne 0 ] ; then
			echo "error with Group $group" 1>&2
			return 1
		fi
		groupid=`dscl . -read /Groups/$group PrimaryGroupID | grep -v "No such key"| awk '{print $2}'`
		;;
		-G)
		members=$2
		;;
		-d)
		homedir=$2
		;;
		-s)
		shell=$2
		;;
		-p)
		password=$2
		;;
		esac
		shift
	done
	dscl . -list /Users/$1 > /dev/null 2>&1
	if [ $? -eq 0 ] ; then
		echo "user $1 exists"
		return 1
	fi
	echo "dscl . -create /Users/$1 UniqueID $userid"
	dscl . -create /Users/$1 UniqueID $userid
	echo "dscl . -create /Users/$1 home $homedir"
	dscl . -create /Users/$1 home $homedir
	echo "dscl . -create /Users/$1 PrimaryGroupID $groupid"
	dscl . -create /Users/$1 PrimaryGroupID $groupid
	echo "dscl . -create /Users/$1 UserShell $shell"
	dscl . -create /Users/$1 UserShell $shell
	echo "dscl . -create /Users/$1 RealName $1"
	dscl . -create /Users/$1 RealName $1
	if [ ! " $password" = " " ] ; then
		echo "dscl . -passwd /Users/$1 xxxxxxxx"
		dscl . -passwd /Users/$1 $password
	fi
	if [ ! " $members" = " " ] ; then
		IFS=,
		j=`echo $members`
		unset IFS
		for i in $j
		do
			echo "dscl . -append /Groups/$i GroupMembership $1"
			dscl . -append /Groups/$i GroupMembership $1 >/dev/null 2>&1
		done
	fi
	if [ $create_home -eq 1 ] ; then
		if [ ! -d $homedir ] ; then
			/bin/mkdir -p $homedir
			/bin/chmod 700 $homedir
			$chown $homedir $userid:$groupid
		fi
	fi
}

linuxuseradd()
{
	userid=""
	group=""
	gecos=""
	members=""
	homedir=""
	shell=""
	password=""
	create_home=1
	nolastlog=0
	args=""

	case "$host" in
		*-*-freebsd*)
		pw=/usr/sbin/pw
		opt1=""
		opt3="-n"
		;;
		*)
		pw=""
		opt1="-r -M"
		opt3=""
		;;
	esac

	while test $# -gt 1; do
		case "$1" in
		-M)
		if [ -f /etc/debian_version -o -n "$pw" ] ; then
			opt2=""
		elif [ -f /bin/busybox ] ; then
			opt2="-H"
		else
			opt2="-M"
		fi
		;;
		-u)
		userid=$2
		;;
		-g)
		group=$2
		;;
		-G)
		members=$2
		;;
		-c)
		gecos=$2
		;;
		-d)
		homedir=$2
		;;
		-s)
		shell=$2
		;;
		-p)
		password=$2
		;;
		-l)
		if [ ! -f /bin/busybox ] ; then
			nolastlog=1
		fi
		;;
		esac
		shift
	done
	getent passwd $1 >/dev/null && echo "user $1 exists" 1>&2 && return 0
	echo "creating user $1"
	if [ -n "$userid" ] ; then
		args="$args -u $userid"
	fi
	if [ -n "$shell" ] ; then
		args="$args -s $shell"
	fi
	if [ -x /bin/busybox ] ; then
		if [ -n "$group" ] ; then
			args="$args -G $group"
		fi
		if [ -n "$homedir" ] ; then
			args="$args -h $homedir"
		fi
		if [ -n "$gecos" ] ; then
			args="$args -g \"$gecos\""
		fi
		echo /usr/sbin/adduser $opt2 $args -D -S $1
		eval /usr/sbin/adduser $opt2 $args -D -S $1
		if [ $? -eq 0 -a -n "$members" ] ; then
			echo /usr/sbin/adduser $1 $members
			eval /usr/sbin/adduser $1 $members
		fi
	else
		if [ -n "$group" ] ; then
			args="$args -g $group"
		fi
		if [ -n "$homedir" ] ; then
			args="$args -d $homedir"
		fi
		if [ -n "$members" ] ; then
			args="$args -G $members"
		fi
		if [ -n "$gecos" ] ; then
			args="$args -c \"$gecos\""
		fi
		if [ -n "$pw" ] ; then
			echo $pw useradd $opt2 $args $opt3 $1
			eval $pw useradd $opt2 $args $opt3 $1
		else
			[ $nolastlog -eq 1 ] && echo /usr/sbin/useradd -l $opt1 $opt2 $args $1 || \
				echo /usr/sbin/useradd $opt1 $opt2 $args $1
			[ $nolastlog -eq 1 ] && eval /usr/sbin/useradd -l $opt1 $opt2 $args $1 || \
				eval /usr/sbin/useradd $opt1 $opt2 $args $1
		fi
	fi
	return $?
}

linuxgroupadd()
{
	args=""
	case "$host" in
		*-*-freebsd*)
		pw=/usr/sbin/pw
		opt1=""
		opt2=""
		opt3="-n"
		;;
		*)
		pw=""
		opt1="-r"
		opt2=""
		opt3=""
		;;
	esac

	groupid=""
	while test $# -gt 1; do
		case "$1" in
		-g)
		groupid=$2
		;;
		esac
		shift
	done
	if [ -n "$groupid" ] ; then
		args="$args -g $groupid"
	fi
	getent group $1 >/dev/null && echo "group $1 exists" 1>&2 && return 0
	echo "creating group $1"
	if [ -x /bin/busybox ] ; then
		echo /usr/sbin/addgroup -S $args $1
		/usr/sbin/addgroup -S $args $1
	else
		if [ -n "$pw" ] ; then
			echo $pw groupadd $args $opt3 $1
			$pw groupadd $args $opt3 $1
		else
			echo /usr/sbin/groupadd $opt1 $args $1
			/usr/sbin/groupadd $opt1 $args $1
		fi
	fi
	return $?
}

create_users()
{
	if [ -f /sbin/nologin ] ; then
		safe_shell=/sbin/nologin
	elif [ -f /usr/bin/false ] ; then
		safe_shell=/usr/bin/false
	elif [ -f /bin/false ] ; then
		safe_shell=/bin/false
	else
		safe_shell=/usr/bin/false
	fi
	(
	for i in nofiles qcerts; do
		case "$host" in
		*-*-darwin*)
		groupid=`dscl . -list /Groups PrimaryGroupID | awk '{print $2}' | sort -n | tail -1`
		groupid=`expr $groupid + 1`
		/usr/bin/dscl . -list Groups/$i >/dev/null 2>&1
		if [ $? -ne 0 ]; then
			echo "creating group $i"
			macOSgroupadd -g $groupid $i
			if [ "$i" = "qcerts" ] ; then
				/usr/bin/dscl . -list Users/apache >/dev/null 2>&1
				if [ $? -eq 0 ] ; then
					echo "added supplementary group qcerts to apache"
					/usr/bin/dscl . append /Groups/qcerts GroupMembership apache
				fi
			fi
		fi
		;;
		*)
		linuxgroupadd $i
		if [ "$i" = "qcerts" ] ; then
			/usr/bin/getent group apache > /dev/null && /usr/sbin/usermod -aG qcerts apache
		fi
		;;
		esac
	done
	case "$host" in
		*-*-darwin*)
		userid=`dscl . -list /Users UniqueID | awk '{print $2}' | sort -n |tail -1`
		userid=`expr $userid + 1`
		/usr/bin/dscl . -list Users/qmaill >/dev/null 2>&1
		if [ $? -ne 0 ]; then
			echo "creating user qmaill"
			macOSuseradd -M -u $userid -g nofiles -d $LOGDIR -s $safe_shell qmaill
		fi
		;;
		*)
		linuxuseradd -c "indimail log user" -M -g nofiles -d $LOGDIR -s $safe_shell qmaill
		;;
	esac
	case "$host" in
		*-*-darwin*)
		loginwindow="/Library/Preferences/com.apple.loginwindow"
		# defaults write /Library/Preferences/com.apple.loginwindow SHOWOTHERUSERS_MANAGED -bool FALSE
		defaults read /Library/Preferences/com.apple.loginwindow SHOWOTHERUSERS_MANAGED >/dev/null
		if [ $? -eq 0 ] ; then
			dscl . create /Users/qmaill IsHidden 1
		else
			defaults read $loginwindow HiddenUsersList | while read line
			do
				if [ " $line" = " (" -o " $line" = " )" ] ; then
					continue
				fi
				line=`echo $line | cut -d, -f1`
				case "$line" in
					qmaill)
					defaults write $loginwindow HiddenUsersList -array-add $line
					;;
					*)
					echo $line
					;;
				esac
			done
		fi
		;;
	esac
	) 2>$TMPDIR/minisvc.user.$$
	if [ -s $TMPDIR/minisvc.user.$$ ] ; then
		/bin/cat $TMPDIR/minisvc.user.$$
		/bin/rm -f $TMPDIR/minisvc.user.$$
		return 1
	else
		/bin/rm -f $TMPDIR/minisvc.user.$$
		return 0
	fi
}

linuxuserdel()
{
	case "$host" in
		*-*-freebsd*)
		pw=/usr/sbin/pw
		;;
		*)
		pw=""
		;;
	esac
	echo "deleting user $1"
	$pw userdel $i
}

linuxgroupdel()
{
	case "$host" in
		*-*-freebsd*)
		pw=/usr/sbin/pw
		;;
		*)
		pw=""
		;;
	esac
	echo "deleting group $1"
	$pw groupdel $i
}

delUsers()
{
	case "$host" in
		*-*-freebsd*)
		pw=/usr/sbin/pw
		;;
		*)
		pw=""
		;;
	esac
	(
	case "$host" in
		*-*-darwin*)
		for i in nofiles; do
			echo "deleting group $i"
			dscl . -delete /Groups/$i
		done
		for i in qmaill; do
			echo "deleting user $i"
			dscl . -delete /Users/$i
		done
		;;
		*)
		for i in nofiles; do
			$linuxgroupdel $i
		done
		for i in qmaill; do
			linuxuserdel $i
		done
		;;
	esac
	) 2>$TMPDIR/minisvc.user.$$
	if [ -s $TMPDIR/minisvc.user.$$ ] ; then
		/bin/cat $TMPDIR/minisvc.user.$$
		/bin/rm -f $TMPDIR/minisvc.user.$$
		return 1
	else
		/bin/rm -f $TMPDIR/minisvc.user.$$
		return 0
	fi
}

create_cert()
{
	if [ $# -ne 3 ] ; then
		echo "minisvc: create_cert postmaster common_name validity_days" 1>&2
			exit 1
	fi
	postmaster=$1
	common_name=$2
	no_of_days=$3
	if [ -n "$certdir" ] ; then
		CERTDIR=$certdir
	else
		CERTDIR=$sysconfdir/certs
	fi
	if [ -z "$postmaster" ] ; then
		echo "postmaster not specified" 1>&2
		exit 1
	fi
	if [ -z "$common_name" ] ; then
		echo "CN not specified" 1>&2
		exit 1
	fi
	if [ ! -x /usr/bin/openssl ] ; then
		echo "/usr/bin/openssl: No such file or directory" 1>&2
		exit 1
	fi
	rand_file=$DESTDIR"$CERTDIR/servercert.rand"
	if [ ! -f $rand_file -o $force -eq 1 ] ; then
		if [ ! -d "$DESTDIR"$CERTDIR ] ; then
			mkdir -p "$DESTDIR"$CERTDIR
		fi
		head -c 512 /dev/urandom > $rand_file
		chown indimail:qcerts $rand_file
		chmod 644 $rand_file
	fi
	conf_file=$DESTDIR"$CERTDIR/servercert.cnf"
	if [ ! -f $conf_file -o $force -eq 1 ] ; then
		echo "Creating SSL Configuration email=$postmaster cn=$common_name"
		create_ssl_cnf $postmaster $common_name > $TMPDIR/config.cnf.$$
		/bin/mkdir -p "$DESTDIR"$CERTDIR
		change_config $conf_file $TMPDIR/config.cnf.$$
		/bin/chmod 640 $conf_file
		$chown root:qcerts $conf_file
	fi
	if [ -f "$DESTDIR"$CERTDIR/servercert.pem -a $force -ne 1 ] ; then
		echo ""$DESTDIR"$CERTDIR/servercert.pem exists. Remove to create new" 1>&2
		exit 1
	fi
	echo "Creating openssl Certificate for $no_of_days days in $CERTDIR/servercert.pem"
	/usr/bin/openssl req -new -x509 -nodes -days $no_of_days -out "$DESTDIR"$CERTDIR/servercert.pem \
		-keyout "$DESTDIR"$CERTDIR/servercert.pem -config $conf_file
	if [ $? -ne 0 ] ; then
		echo "Failed to create openssl x509 certificate" 1>&2
		exit 1
	fi
	/bin/chmod 640 "$DESTDIR"$CERTDIR/servercert.pem
	$chown root:qcerts "$DESTDIR"$CERTDIR/servercert.pem
	if [ -f "$DESTDIR"$CERTDIR/clientcert.pem ] ; then
		t=$(readlink "$DESTDIR"$CERTDIR/clientcert.pem)
		t=$(basename $t)
		if [ ! "$t" = "servercert.pem" ] ; then
			/bin/rm -f "$DESTDIR"$CERTDIR/clientcert.pem
		fi
	fi
	if [ ! -f "$DESTDIR"$CERTDIR/clientcert.pem ] ; then
		cd "$DESTDIR"$CERTDIR
		/bin/ln -s servercert.pem \
			clientcert.pem 2>/dev/null
		if [ $? -ne 0 ] ; then
			echo "Failed to link clientcert.pem to servercert.pem" 1>&2
			exit 1
		fi
	fi
	echo "Updating temporary RSA and DH keys"
	if [ -x "$DESTDIR"$libexecdir/update_tmprsadh ] ; then
		"$DESTDIR"$libexecdir/update_tmprsadh --certdir="$DESTDIR"$CERTDIR
	elif [ -x $libexecdir/update_tmprsadh ] ; then
		$libexecdir/update_tmprsadh --certdir="$DESTDIR"$CERTDIR
	else
		echo "$libexecdir/update_tmprsadh: No such file or directory" 1>&2
		echo "generate RSA/DH parameters manually" 1>&2
	fi

	updated=0
	if [ $updatecerts -eq 1 ] ; then
		svc_list=""
		echo "Fixing CERTDIR variable for services"
		for i in /service/*/variables/CERTDIR
		do
			j=$(/usr/bin/cat $i 2>/dev/null)
			if [ ! " $j" = " $CERTDIR" ] ; then
				updated=1
				echo "Fixed $i"
				echo $CERTDIR > $i
				x=$(echo $i | cut -d'/' -f1,2,3)
				if [ -z "$svc_list" ] ; then
					svc_list="$x"
				else
					svc_list="$svc_list $x"
				fi
			else
				echo "$i: OK"
			fi
		done

		echo "Updating CERT as $CERTDIR/servercert.pem"
		for i in `ls /service/*/variables/*CERTFILE \
			/service/*/variables/CLIENTCERT \
			/service/*/variables/SERVERCERT 2>/dev/null`
		do
			x=$(echo $i | cut -d'/' -f1,2,3)
			echo $svc_list | grep $x >/dev/null
			if [ $? -ne 0 ] ; then
				if [ -z "$svc_list" ] ; then
					svc_list="$x"
				else
					svc_list="$svc_list $x"
				fi
			fi
			j=$(/usr/bin/cat $i)
			if [ ! " $j" = " $CERTDIR/servercert.pem" ] ; then
				echo "Fixed $i"
				updated=1
				echo "$CERTDIR/servercert.pem" > $i
			else
				echo "$i: OK"
			fi
		done
		if [ -f /usr/bin/imapd ] ; then
			echo "Updating TLS CACHE as $CERTDIR/couriersslcache"
			for i in `ls /service/*/variables/TLS_CACHEFILE 2>/dev/null`
			do
				j=$(/usr/bin/cat $i)
				if [ ! " $j" = " $CERTDIR/couriersslcache" ] ; then
					echo "Fixed $i"
					echo "$CERTDIR/couriersslcache" > $i
					updated=1
					x=$(echo $i | cut -d'/' -f1,2,3)
					echo $svc_list | grep $x >/dev/null
					if [ $? -ne 0 ] ; then
						if [ -z "$svc_list" ] ; then
							svc_list="$x"
						else
							svc_list="$svc_list $x"
						fi
					fi
				else
					echo "$i: OK"
				fi
			done
		fi
	else
		if [ -f /usr/bin/imapd ] ; then
			echo "--update-certs not given. Skipping updating Services for CERTDIR, CERTFILE and TLS_CACHE" 1>&2
		else
			echo "--update-certs not given. Skipping updating Services for CERTDIR, CERTFILE" 1>&2
		fi
	fi

	echo "====== Certificate $CERTDIR/servercert.pem ========="
	/usr/bin/openssl x509 -in "$DESTDIR"$CERTDIR/servercert.pem -noout -text
	echo "================================================================"

	# restart services
	if [ $updated -eq 1 ] ; then
		echo "Restarting services using $CERTDIR/servercert.pem"
		for i in $svc_list; do echo "Restarting service $i"; done
		svc -r $svc_list
	fi
}

tls_cert_check()
{
if [ ! -x /usr/bin/openssl ] ; then
	echo "/usr/bin/openssl: No such file or directory" 1>&2
	return 1
fi
error=0
if [ $# -eq 1 ] ; then
	files=$1
else
	files="$sysconfdir/certs/servercert.pem $sysconfdir/certs/clientcert.pem"
fi
for cert in $files
do
	if [ -f $cert ]; then
		echo "Checking $cert"
		#First, check that it's a valid cert for the task
		TEMP_PURPOSE=`/usr/bin/openssl x509 -in $cert -noout -purpose 2>/dev/null`
		if [ "$?" != "0" ]; then
			error=1
			dir=`dirname $cert`
			fil=`basename $cert`
			$mv -f $cert $dir/BROKEN-${fil}
			if [ $? -eq 0 ] ; then
				echo $TEMP_PURPOSE 1>&2
				echo "$cert is a broken cert. Disabled" 1>&2
			fi
		fi

		#Now check it hasn't expired
		TEMP_DATE=`/usr/bin/openssl x509 -in $cert -noout -dates 2>/dev/null|grep -i after|cut -d= -f2`
		case "$host" in
			*-*-darwin*|*-*-freebsd*)
			EXPIRE_IN_SECS=`date -j -f "%b %d %T %Y %Z" "$TEMP_DATE" "+%s"`
			;;
			*)
			EXPIRE_IN_SECS=`date +%s --date $TEMP_DATE 2>/dev/null`
			;;
		esac
		if [ "`echo $EXPIRE_IN_SECS|grep -E '^[0-9]+$'`" != "" ]; then
			NOW_IN_SECS=`date +%s 2>/dev/null`
			if [ "`echo $NOW_IN_SECS|grep -E '^[0-9]+$'`" != "" ]; then
				if [ $NOW_IN_SECS -gt $EXPIRE_IN_SECS ]; then
					error=1
					echo expiry $TEMP_DATE 1>&2
					dir=`dirname $cert`
					fil=`basename $cert`
					$mv -f $cert $dir/EXPIRED-${fil}
					if [ $? -eq 0 ] ; then
						echo "$cert has EXPIRED. Disabling" 1>&2
					fi
				fi
			fi
		fi

		if [ "`echo $cert|grep server`" != "" ];then
			if [ "`echo $TEMP_PURPOSE|grep -Ei '(any purpose|server).* yes'`" = "" ]; then
				error=1
				echo "Purpose $TEMP_PURPOSE" 1>&2
				dir=`dirname $cert`
				fil=`basename $cert`
				$mv -f $cert $dir/NOT-A-SERVER-CERT-${fil}
				if [ $? -eq 0 ] ; then
					echo "$cert is NOT a server cert. Disabled" 1>&2
				fi
			fi
		fi
		if [ "`echo $cert|grep client`" != "" ];then
			if [ "`echo $TEMP_PURPOSE|grep -Ei '(any purpose|client).* yes'`" = "" ]; then
				error=1
				echo "Purpose $TEMP_PURPOSE" 1>&2
				dir=`dirname $cert`
				fil=`basename $cert`
				$mv -f $cert $dir/NOT-A-CLIENT-CERT-${fil}
				if [ $? -eq 0 ] ; then
					echo "$cert is NOT a client cert. Disabled" 1>&2
				fi
			fi
		fi
	fi
done
if [ $error -eq 0 ] ; then
	echo "All Certificates found OK. Press ENTER to view Certificates"
	read key
	(
	for cert in $files; do
		echo "==== Certificate $cert ========="
		if [ -L $cert ] ; then
			echo "Linked to $(readlink $cert)"
			ls -ld $cert
		else
	 		openssl x509 -in $cert -text
		fi
	 	echo ================================================================
		echo
	done
	) | $MORE
fi
}

################################# Main ##################################
if test $# -eq 0; then
    usage 1
fi
if [ -x /bin/chown ] ; then
	chown=/bin/chown
elif [ -x /usr/sbin/chown ] ; then
	chown=/usr/sbin/chown
elif [ -x /usr/bin/chown ] ; then
	chown=/usr/bin/chown
else
	chown=/bin/chown
fi
if [ $(id -u) -ne 0 ] ; then
	echo "minisvc is not meant to be run by mere mortals. Use sudo to get superpowers"
	exit 100
fi

if [ -f /etc/indimail/svctool.cnf ] ; then
	perms=$(stat -c "%u:%g:%a" $sysconfdir/svctool.cnf)
	if [ $? -ne 0 ] ; then
		exit 100
	fi
	if [ ! $perms = "0:0:400" ] ; then
		echo "fixing permissions of svctool.cnf"
		$chown root:0 /etc/indimail/svctool.cnf
		/bin/chmod 400 /etc/indimail/svctool.cnf
	fi
	. /etc/indimail/svctool.cnf
fi
[ -z "$TMPDIR" ] && TMPDIR="/tmp/minisvc"
[ ! -d "$TMPDIR" ] && mkdir -m 0700 -p $TMPDIR

if [ ! -d $TMPDIR ] ; then
	echo "$TMPDIR: No such file or directory" 1>&2
	exit 1
fi

prog_args="$prefix/sbin/minisvc"
force=0
silent=0
down_state=0
use_unshare=0
nooverwrite=0
run_file_only=0
mount_resolvconf=0
valid_for=366
usefsync=0
usefdatasync=0
usesyncdir=0
updatecerts=0
verbose=""

if [ " $CONTROLDIR" = " " ] ; then
	cntrldir=$sysconfdir/control
else
	slash=`echo $CONTROLDIR | cut -c1`
	if [ " $slash" = " /" ] ; then
		cntrldir=$CONTROLDIR
	else
		cntrldir=$sysconfdir/$CONTROLDIR
	fi
fi
CONTROLDIR=$cntrldir
export CONTROLDIR
if [ -f $cntrldir/servicedir.conf ] ; then
	servicedir=`cat $cntrldir/servicedir.conf`
else
	servicedir=/service
fi

while test $# -gt 0; do
    case "$1" in
    -*=*)
	optarg=`echo "$1" | sed 's/[-_a-zA-Z0-9]*=//'`
	optval=`echo "$1" | cut -d'=' -f1`
	prog_args="$prog_args $optval=\"$optarg\""
	;;
    *)
	optarg=
	prog_args="$prog_args $1"
	;;
    esac

    case "$1" in
    --verbose)
	verbose="-v"
	;;
    --servicedir=*)
	servicedir=$optarg
	;;
	--memory=*)
	memory=$optarg
	;;
	--dmemory=*)
	dmemory=$optarg
	;;
	--servicetag=*)
	servicetag=$optarg
	;;
    --logdir=*)
	LOGDIR=$optarg
	export LOGDIR
	;;
	--force)
	force=1
	;;
	--sysconfdir=*)
	mysysconfdir=$optarg
	;;
	--nolog)
	nolog=1
	;;

	--silent)
	silent=1
	;;

	--destdir=*)
	DESTDIR=$optarg
	;;

	--down)
	down_state=1
	;;
	--unshare)
	use_unshare=1
	;;

	--config=*)
	if [ " $option" = " " ] ; then
		option=1
		config_name=$optarg
	else
		conf_file=$optarg
	fi
	;;

	--rmsvc=*)
	option=2
	service=$optarg
	;;

	--ensvc=*)
	option=3
	service=$optarg
	;;

	--refreshsvc=*)
	option=4
	service=$optarg
	;;

	--autorefresh=*)
	option=5
	service=$optarg
	;;

	--nooverwrite)
	nooverwrite=1
	;;

	--svscanlog)
	option=6
	;;

	--resolvconf)
	mount_resolvconf=1
	;;

	--initcmd=*)
	svscan_init_cmd=$optarg
	;;

	--scanint=*)
	scan_interval=$optarg
	;;

	--run-file-only)
	if [ $option -eq 34 ] ; then
		run_file_only=1
	fi
	;;

	--mode=*)
	group=$optarg
	;;
	--owner=*)
	owner=$optarg
	;;
	--group=*)
	group=$optarg
	;;
	--service-name=*)
	service_name=$optarg
	;;
	--envdir=*)
	envdir=$optarg
	;;
	--variable-value=*)
	variable_value=$optarg
	;;
	--set-variable=*)
	variable_name=$optarg
	option=7
	;;
	--modify-variable=*)
	variable_name=$optarg
	option=8
	;;
	--unset-variable=*)
	variable_name=$optarg
	option=9
	;;
	--remove-variable=*)
	variable_name=$optarg
	option=10
	;;
	--restore-variables)
	option=11
	;;
	--import-variables=*)
	option=12
	env_file=$optarg
	;;
	--export-variables=*)
	option=13
	env_file=$optarg
	;;
	--save-variables)
	option=14
	;;
	--restore-all-variables)
	option=15
	;;
	--dumpconfig)
	option=16
	;;
	--print-variables)
	option=17
	;;
	--print-all-variables)
	option=18
	;;

	--enable-service)
	option=19
	service=$optarg
	break
	;;

	--disable-service)
	option=20
	service=$optarg
	break
	;;

	--capath=*)
	ca_path=$optarg
	;;
	--certdir=*)
	certdir=$optarg
	;;
	--update-certs)
	updatecerts=1
	;;
	--postmaster=*)
	postmaster=$optarg
	;;
	--common_name=*)
	common_name=$optarg
	;;
	--validity_days=*)
	valid_for=$optarg
	;;
	--check-certs)
	cert_file=""
	option=21
	;;

	--check-certs=*)
	cert_file=$optarg
	option=21
	;;

	--version)
	echo "$RCSID"
	exit 0
	;;

	--help)
	usage 0
	;;

	*)
	echo "invalid option [$1]" 1>&2
	read key
	usage 1
	;;
	esac
	shift
done

#
# Main
#
if [ " $CONTROLDIR" = " " ] ; then
	cntrldir=/etc/indimail/control
else
	slash=`echo $CONTROLDIR | cut -c1`
	if [ " $slash" = " /" ] ; then
		cntrldir=$CONTROLDIR
	else
		cntrldir=$sysconfdir/$CONTROLDIR
	fi
fi
CONTROLDIR=$cntrldir
export CONTROLDIR
case $option in
	1)
	# config creation for --config option
	# Check that we're a privileged user
	case $config_name in
		add-boot)
		case "$host" in
			*-*-darwin*)
			if [ -z "$servicedir" ] ; then
				echo "Supervise Directory not specified" 1>&2
				usage 1
			fi
			;;
		esac
		create_startup
		;;

		rm-boot)
		remove_startup
		;;

		users)
		nscd_up=`ps ax |grep nscd |grep -v grep|wc -l`
		if [ $nscd_up -ge 1 ] ; then
			if [ -x /etc/init.d/nscd ] ; then
				/etc/init.d/nscd stop
  			elif [ -f /etc/systemd/system/multi-user.target/nscd.service ] ; then
    			/bin/systemctl stop nscd.service
			fi
		fi
		create_users
		status=$?
		if [ $nscd_up -ge 1 ] ; then
			if [ -x /etc/init.d/nscd ] ; then
				/etc/init.d/nscd start
  			elif [ -f /etc/systemd/system/multi-user.target/nscd.service ] ; then
    			/bin/systemctl start nscd.service
			fi
		fi
		exit $status
		;;

		rmusers)
		delUsers
		;;

		inittab)
		# Check that we're a privileged user
		if [ " $servicedir" = " " ] ; then
			echo "Supervise Directory not specified" 1>&2
			usage 1
		fi
		grep "svscanboot" /etc/inittab >/dev/null
		if [ $? -ne 0 ]; then
			if [ -f /etc/debian_release ] ; then
				echo "SV:2345:respawn:$libexecdir/svscanboot $servicedir" >> /etc/inittab
			elif [ -f /etc/alpine-release ] ; then
				echo "::respawn:$libexecdir/svscanboot $servicedir" >> /etc/inittab
			else
				echo "SV:345:respawn:$libexecdir/svscanboot $servicedir" >> /etc/inittab
			fi
			if [ $? -eq 0 ] ; then
				kill -1 1
			fi
		else
			grep "svscanboot" /etc/inittab |grep respawn >/dev/null
			if [ $? -ne 0 ]; then
				grep -v "svscanboot" /etc/inittab > /etc/inittab.minisvc.$$
				if [ $? -eq 0 ] ; then
					if [ -f /etc/debian_release ] ; then
						echo "SV:345:respawn:$libexecdir/svscanboot $servicedir" >> /etc/inittab.minisvc.$$
					elif [ -f /etc/alpine-release ] ; then
						echo "::respawn:$libexecdir/svscanboot $servicedir" >> /etc/inittab
					else
						echo "SV:2345:respawn:$libexecdir/svscanboot $servicedir" >> /etc/inittab.minisvc.$$
					fi
				fi
				if [ $? -eq 0 ] ; then
					/bin/mv /etc/inittab.minisvc.$$ /etc/inittab
					kill -1 1
				fi
			fi
		fi
		;;

		cert)
		create_cert "$postmaster" "$common_name" $valid_for
		;;


		*)
		echo "Invalid configuration option $optarg" 1>&2
		usage 1
		;;
	esac
	;;

	2) # remove service
	# Check that we're a privileged user
	rmsvc "$service"
	;;

	3) # enable servie
	# Check that we're a privileged user
	ensvc "$service"
	;;

	4)
	if [ " $servicedir" = " " ] ; then
		echo "Supervise Directory not specified" 1>&2
		usage 1
	fi
	refreshsvc $service
	;;

	5)
	if [ " $servicedir" = " " ] ; then
		echo "Supervise Directory not specified" 1>&2
		usage 1
	fi
	autorefresh $service
	;;

	6)
	# Check that we're a privileged user
	if [ " $servicedir" = " " ] ; then
		echo "Supervise Directory not specified" 1>&2
		usage 1
	fi
	echo "Creating svscan log Service Service $servicedir"
	create_svscan $servicedir $svscan_init_cmd
	;;

	7|8|9|10) # set, modify, unset variables
	if [ -z "$servicedir" ] ; then
		echo "Supervise Directory not specified" 1>&2
		usage 1
	fi
	if [ -z "$service_name" ] ; then
		echo "service name not specified" 1>&2
		usage 1
	fi
	if [ -z "$variable_name" ] ; then
		echo "variable name not specified" 1>&2
		usage 1
	fi
	if [ ! -d $servicedir/$service_name ] ; then
		echo "$servicedir/$service_name: No such file or directory" 1>&2
		exit 1
	fi
	case $option in
		7) #set variable
		if [ $force -ne 1 -a -f $servicedir/$service_name/variables/$variable_name ] ; then
			echo "$variable_name exists. Use --force to overwrite" 1>&2
			usage 1
		fi
		;;
		8) # modify variable
		if [ $force -ne 1 -a ! -f $servicedir/$service_name/variables/$variable_name ] ; then
			echo "$variable_name does not exists. Use --force to create" 1>&2
			usage 1
		fi
		;;
		9) # unset variable
		echo "unsetting env variable $variable_name"
		> $servicedir/$service_name/variables/$variable_name
		;;
		10) # delete variable
		echo "removing env variable $variable_name"
		/bin/rm -f $servicedir/$service_name/variables/$variable_name
		;;
	esac
	if [ -z "$owner" ] ; then
		owner=root
	fi
	if [ -z "$group" ] ; then
		group=0
	fi
	if [ -z $mode ] ; then
		mode=0640
	fi
	dir=$servicedir/$service_name
	if [ $option -eq 7 -o $option -eq 8 ] ; then
		if [ -n "$variable_value" ] ; then
			echo "setting env variable $variable_name=[$variable_value]"
			echo $variable_value > $dir/variables/$variable_name
		else
			echo "setting env variable $variable_name"
			echo > $dir/variables/$variable_name
		fi
	fi
	old=$force
	force=1
	if [ $silent -eq 0 ] ; then
		printf "export %-35s %s %s %s\n" "`dirname $dir`" $owner $group $mode
	fi
	export_variables $dir/variables $dir/variables/.variables $owner $group $mode
	force=$old
	if [ $option -ne 10 ] ; then
		if [ -n "$mode" ] ; then
			/bin/chmod $mode $dir/variables/$variable_name
		fi
		if [ -n "$owner" -a -n "$group" ] ; then
			$chown $owner:$group $dir/variables/$variable_name
		elif [ -n "$owner" ] ; then
			$chown $owner $dir/variables/$variable_name
		fi
	fi
	;;

	11|12|13) # restore variables, import variables, export variables
	if [ -z "$servicedir" ] ; then
		echo "Supervise Directory not specified" 1>&2
		usage 1
	fi
	if [ -z "$service_name" ] ; then
		echo "service name not specified" 1>&2
		usage 1
	fi
	if [ ! -d $servicedir/$service_name ] ; then
		echo "$servicedir/$service_name: No such file or directory" 1>&2
		exit 1
	fi
	if [ -z "$owner" ] ; then
		owner=root
	fi
	if [ -z "$group" ] ; then
		group=0
	fi
	if [ -z $mode ] ; then
		mode=0640
	fi
	if [ $option -eq 11 ] ; then
		file=$servicedir/$service_name/variables/.variables
		if [ ! -f $file ] ; then
			echo "env file for $service_name (.variables) doesn't exist" 1>&2
			usage 1
		fi
	elif [ $option -eq 12 ] ; then
		file=$env_file
		if [ ! -f $file ] ; then
			echo "$file: No such file or directory" 1>&2
			usage 1
		fi
	else
		file=$(basename $env_file)
	fi
	if [ $option -eq 11 ] ; then   # restore variables to original state
		import_variables $servicedir/$service_name/variables $file 1 $owner $group $mode
	elif [ $option -eq 12 ] ; then # import new variables
		import_variables $servicedir/$service_name/variables $file 0 $owner $group $mode
	else
		dir="$servicedir/$service_name"
		if [ $silent -eq 0 ] ; then
			printf "export %-35s %s %s %s\n" "$dir" $owner $group $mode
		fi
		if [ ! "$dir/variables/$file" = "$env_file" ] ; then
			old=$force
			force=1
			export_variables $dir/variables $env_file $owner $group $mode
			force=$old
		else
			export_variables $dir/variables $dir/variables/$file $owner $group $mode
		fi
	fi
	;;

	14)
	if [ -z "$servicedir" ] ; then
		echo "Supervise Directory not specified" 1>&2
		usage 1
	fi
	save_all_variables
	;;
	15)
	if [ -z "$servicedir" ] ; then
		echo "Supervise Directory not specified" 1>&2
		usage 1
	fi
	restore_all_variables
	;;

	16) # dump config
	if [ " $servicedir" = " " ] ; then
		echo "Supervise Directory not specified" 1>&2
		usage 1
	fi
	dump_config "$servicedir" "$cntrldir"
	;;
	17)
	if [ -z "$servicedir" ] ; then
		echo "Supervise Directory not specified" 1>&2
		usage 1
	fi
	if [ -n "$service_name" -a -n "$envdir" ] ; then
		echo "you cannot specify both service name and envdir both" 1>&2
		exit 1
	fi
	if [ -z "$service_name" -a -z "$envdir" ] ; then
		echo "service name or envdir has to be specified" 1>&2
		usage 1
	fi
	if [ -n "$service_name" -a ! -d $servicedir/$service_name ] ; then
		echo "$servicedir/$service_name: No such file or directory" 1>&2
		exit 1
	fi
	if [ -n "$envdir" -a ! -d "$envdir" ] ; then
		echo "$envdir: No such directory" 1>&2
		exit 1
	fi
	if [ -n "$service_name" ] ; then
		i=$servicedir/$service_name/variables
	elif [ -n "$envdir" ] ; then
		i=$envdir
	fi
	if [ ! -d $i ] ; then
		(
		echo "------ $servicedir/$service_name ------------" 
		echo "NOTE: This service has no configured variables"
		) 1>&2
		exit 1
	fi
	if [ -L $i/.envdir -o -f $i/.envdir -o -f $i/.envfile ] ; then
		if [ -n "$service_name" ] ; then
			echo "------ $servicedir/$service_name ------------"
		elif [ -n "$envdir" ] ; then
			echo "------ $envdir ------------"
		fi
	fi
	if [ -L $i/.envdir ] ; then
		link_name=$(readlink $i/.envdir)
		echo "NOTE: additional variables were obtained from $link_name"
		echo
	elif [ -f $i/.envdir ] ; then
		echo "NOTE: additional variables were obtained from .envdir"
		cat $i/.envdir
		echo
	fi
	if [ -f $i/.envfile ] ; then
		echo "NOTE: additional variables were obtained from .envfile"
		cat $i/.envfile
		echo
	fi
	if [ -n "$service_name" ] ; then
		echo "------ environment variables for $servicedir/$service_name ------------"
	elif [ -n "$envdir" ] ; then
		echo "------ environment variables for $envdir ------------"
	fi
	envdir -c $i env
	;;

	18)
	if [ -z "$servicedir" ] ; then
		echo "Supervise Directory not specified" 1>&2
		usage 1
	fi
	for i in $servicedir/*
	do
		if [ -d $i/variables ] ; then
			vars=$(envdir -c $i/variables env 2>/dev/null)
			if [ -n "$vars" ] ; then
				echo "------ environment variables for $i ------------"
				envdir -c $i/variables env
				echo
				if [ -L $i/variables/.envdir ] ; then
					link_name=$(readlink $i/variables/.envdir)
					echo "NOTE: additional variables were obtained from $link_name"
					echo
				elif [ -f $i/variables/.envdir ] ; then
					echo "NOTE: additional variables were obtained from .envdir"
					cat $i/variables/.envdir
					echo
				fi
				if [ -f $i/variables/.envfile ] ; then
					echo "NOTE: additional variables were obtained from .envfile"
					cat $i/variables/.envfile
					echo
				fi
			else
				echo "------ $i ------------"
				echo "NOTE: This service has no configured variables"
				echo
			fi
		fi
	done
	for i in $sysconfdir/control/defaultqueue $sysconfdir/control/global_vars \
		$sysconfdir/ezmlm/global_vars
	do
		if [ -d $i ] ; then
			vars=$(envdir -c $i env 2>/dev/null)
			if [ -n "$vars" ] ; then
				echo "------ environment variables for $i ------------"
				envdir -c $i env
				echo
				if [ -L $i/.envdir ] ; then
					link_name=$(readlink $i/.envdir)
					echo "NOTE: additional variables were obtained from $link_name"
					echo
				elif [ -f $i/.envdir ] ; then
					echo "NOTE: additional variables were obtained from .envdir"
					cat $i/.envdir
					echo
				fi
				if [ -f $i/.envfile ] ; then
					echo "NOTE: additional variables were obtained from .envfile"
					cat $i/.envfile
					echo
				fi
			else
				echo "------ $i ------------"
				echo "NOTE: This directory has no configured variables"
				echo
			fi
		fi
	done
	;;

	19) # enable service
	shift
	enable_service $*
	;;

	20) # disable service
	shift
	disable_service $*
	;;

	21) # check-certs
	if [ -z "$cert_file" ] ; then
		tls_cert_check
	else
		tls_cert_check $cert_file
	fi
	;;

	*)
	if [ " $option" = " " ] ; then
		echo "No Options Provided" 1>&2
		read key
	else
		echo "Invalid Option [$option]" 1>&2
	fi
	;;
esac

if [ ! " $prog_args" = " " ] ; then
	if [ " $nolog" = " " ] ; then
		if [ ! -d "$DESTDIR"$LOGDIR ] ; then
			/bin/mkdir -p "$DESTDIR"$LOGDIR
		fi
		echo "`date` $prog_args" >> "$DESTDIR"$LOGDIR/services.log
	fi
fi
exit 0
#
# $Log: minisvc.in,v $
# Revision 1.40  2024-11-05 22:32:40+05:30  Cprogrammer
# svscan shutdown to umount only when UNSHARE variable is set and /etc/indimail/resolv.conf exists
#
# Revision 1.39  2024-04-29 16:29:47+05:30  Cprogrammer
# fix for missing qmail group
#
# Revision 1.38  2024-03-11 17:42:15+05:30  Cprogrammer
# updated RCS log
#
# Revision 1.37  2023-12-29 23:38:07+05:30  Cprogrammer
# added missing definitions for usefsync, usefdatasync, usesyncdir
#
# Revision 1.36  2023-07-01 11:24:48+05:30  Cprogrammer
# skip indimail-mta variables when creating svscan service
#
# Revision 1.35  2023-05-03 16:50:28+05:30  Cprogrammer
# synced daemontools/minisvc, indimail-mta/svctool create_svscan function
#
# Revision 1.34  2022-11-14 19:57:33+05:30  Cprogrammer
# when importing variables don't treat existing variables as error
#
# Revision 1.33  2022-11-09 20:13:17+05:30  Cprogrammer
# replaced deprecated egrep with grep -E
#
# Revision 1.32  2022-08-20 12:14:18+05:30  Cprogrammer
# skip lead space, comments, blank lines when converting envfile to envdir
#
# Revision 1.31  2022-06-20 00:48:04+05:30  Cprogrammer
# Fixes for OSX
#
# Revision 1.30  2021-08-26 12:41:46+05:30  Cprogrammer
# use /usr/local/etc/indimail/sv for servicedir on OSX/Darwin
#
# Revision 1.29  2021-08-17 13:19:27+05:30  Cprogrammer
# added --config=cert option
# added --check-certs option
#
# Revision 1.28  2021-08-15 01:37:05+05:30  Cprogrammer
# fixed missing wsp in test condition
#
# Revision 1.27  2021-07-28 12:36:58+05:30  Cprogrammer
# renamed boot/svscan to boot/openrc for alpine
#
# Revision 1.26  2021-07-25 23:05:42+05:30  Cprogrammer
# minor change in print-all-variables output
#
# Revision 1.25  2021-07-25 15:48:41+05:30  Cprogrammer
# install openrc script for alpine linux
#
# Revision 1.24  2021-07-24 19:23:15+05:30  Cprogrammer
# removed hardcoding of mount and umount
#
# Revision 1.23  2021-07-24 18:11:54+05:30  Cprogrammer
# added --config for users rmusers inittab
# added --resolvconf option
# added --enable-service --disable-service
#
# Revision 1.22  2021-07-17 08:44:48+05:30  Cprogrammer
# --norefreshsvc renamed to --autorefresh
#
# Revision 1.21  2021-07-16 18:50:05+05:30  Cprogrammer
# added --print-all-variables option
#
# Revision 1.20  2021-07-07 19:25:55+05:30  Cprogrammer
# added --print-variables option
#
# Revision 1.19  2021-05-16 16:47:42+05:30  Cprogrammer
# fixed TMPDIR creation
#
# Revision 1.18  2021-05-13 14:53:36+05:30  Cprogrammer
# fixed permissions of env variables in defaultqueue
#
# Revision 1.17  2021-05-06 09:21:18+05:30  Cprogrammer
# remove mixed uses of space and tab
#
# Revision 1.16  2021-05-03 09:29:02+05:30  Cprogrammer
# do systemctl daemon-reload after installing, updating or removing svscan service
#
# Revision 1.15  2021-04-28 11:22:14+05:30  Cprogrammer
# allow --force to override norefreshsvc flag for a service
#
# Revision 1.14  2021-04-20 13:48:56+05:30  Cprogrammer
# honour --silent in export variables
#
# Revision 1.13  2021-04-20 09:13:51+05:30  Cprogrammer
# make output less verbose with --silent parameter
#
# Revision 1.12  2021-04-16 16:23:16+05:30  Cprogrammer
# fixed typo
#
# Revision 1.11  2021-04-16 10:54:33+05:30  Cprogrammer
# added additional checks when enabling, disabling supervise services
#
# Revision 1.10  2021-04-15 18:26:39+05:30  Cprogrammer
# take into account /run filesystem when enabling, disabling service
#
# Revision 1.9  2021-04-05 07:20:31+05:30  Cprogrammer
# fixed --export-variables
#
# Revision 1.8  2021-02-28 21:26:00+05:30  Cprogrammer
# updated help message
#
# Revision 1.7  2021-02-28 17:23:09+05:30  Cprogrammer
# use common functions dump_run_header, dump_log_header for generating run, log/run
#
# Revision 1.6  2021-02-27 17:23:08+05:30  Cprogrammer
# added options to set, unset, remove env variables for supervised services
#
# Revision 1.5  2020-11-29 17:51:10+05:30  Cprogrammer
# fixed syntax error
#
# Revision 1.4  2020-10-23 21:28:54+05:30  Cprogrammer
# fix chmod of .svscan/run
#
# Revision 1.3  2020-10-23 21:12:49+05:30  Cprogrammer
# create svscan run script, resolv.conf only when unshare is present
#
# Revision 1.2  2020-10-23 13:54:12+05:30  Cprogrammer
# fixed option
#
# Revision 1.1  2020-10-21 20:31:26+05:30  Cprogrammer
# Initial revision
#
#
