#!/bin/bash
#
CMD=$(basename "$0")
CMDVER="1.1"
CMDSTR="$CMD v$CMDVER (2022-02-16)"

set -e -u

usage()
{
	echo -e"
== $CMDSTR == setup/check DKIM stuffs ==

usage: $CMD {-n|-x} [options] [domain(s)...]

options:
  -x|--execute	do stuffs (default: dry-run)
  -n|--dry-run	dry-run (default, ignored)

default domains list is got from $domainsfile:

exits:
  0	all ok, no changes
  254	all ok, changes was made
  any	any other value is an error
" >&2
	echo " " $default_domains | fold >&2
	echo "" >&2
	exit 127
}


# (MAIN)

F_exec=
Dummy=
dry_run_opt=
here=$(pwd)
dkim_dir="dkim.d"
domains=
domainsfile="virtual.d/_domains"
default_domains=
changes=false

dkim_user=$(kusa-conf dkim.user 2>/dev/null || echo "opendkim")
dkim_group=$(kusa-conf dkim.group 2>/dev/null || echo "opendkim")
dkim_owner="$dkim_user:$dkim_group"

[ -s "$dkim_dir/domains" ]	&& domainsfile="$dkim_dir/domains"
[ -s "$domainsfile" ]		&& default_domains=$(cat "$domainsfile")

while [ $# != 0 ]
do
  case $1 in
    -n|--dry-run)	F_exec=false; dry_run_opt="-n"; Dummy="echo (dummy)" ;;
    -x|--execute)	F_exec=true; dry_run_opt=; Dummy= ;;
    -*|"")		usage ;;
    *)			domains="$domains $1" ;;
  esac
  shift
done
[ "X$F_exec" = "X" ] && usage

domains=${domains:-$default_domains}


[ -d "$dkim_dir" ] || {
	echo "  creating dir '$dkim_dir'"
	$Dummy mkdir "$dkim_dir"
}

key_table="$dkim_dir/key_table"
signing_table="$dkim_dir/signing_table"

:>"$key_table.new"
:>"$signing_table.new"

for domain in $domains
do
	cd "$here"

	ddir="$dkim_dir/$domain"

	echo "  checking domain: $domain"

	[ -d "$ddir" ] || {
		echo "   creating dir: $ddir"
		$Dummy mkdir "$ddir"
	}

	cd "$ddir"

	[ -f mail.private -a -f mail.txt ] || {
		echo "   generating keys for $domain"
		$Dummy opendkim-genkey -v -r -t -s mail -d $domain
		changes=true
	}

	[ -f mail.key ] || {
		echo "   generating config file: mail.key"
		$F_exec && {
			echo "*@$domain:$domain:$here/$ddir/mail.private" >mail.key
		}
		changes=true
	}

	cd "$here"

	echo "$domain $domain:mail:$here/$ddir/mail.private" >>"$key_table.new"

	echo "*@$domain $domain" >>"$signing_table.new"

	ls -l "$ddir/mail.private" "$ddir/mail.txt" "$ddir/mail.key" || :
	echo

done

jtinstall $dry_run_opt --inform "$key_table.new" "$key_table" $dkim_owner 440 || {
	[ $? != 254 ] && exit 1
	changes=true
}
jtinstall $dry_run_opt --inform "$signing_table.new" "$signing_table" $dkim_owner 440 || {
	[ $? != 254 ] && exit 1
	changes=true
}

rm -f "$key_table.new" "$signing_table.new"

$changes && exit 254
exit 0
