#!/bin/bash

set -e

do_pre_regen() {
  pending_dir=$1

  cd /usr/share/yunohost/templates/rspamd

  install -D -m 644 metrics.local.conf \
      "${pending_dir}/etc/rspamd/local.d/metrics.conf"
  install -D -m 644 dkim_signing.conf \
      "${pending_dir}/etc/rspamd/local.d/dkim_signing.conf"
  install -D -m 644 rspamd.sieve \
      "${pending_dir}/etc/dovecot/global_script/rspamd.sieve"
}

do_post_regen() {

  ##
  ## DKIM key generation
  ##

  # create DKIM directory with proper permission
  mkdir -p /etc/dkim
  chown _rspamd /etc/dkim

  # create DKIM key for domains
  for domain in $YNH_DOMAINS; do
    domain_key="/etc/dkim/${domain}.mail.key"
    [ ! -f "$domain_key" ] && {
      # We use a 1024 bit size because nsupdate doesn't seem to be able to
      # handle 2048...
      opendkim-genkey --domain="$domain" \
          --selector=mail --directory=/etc/dkim -b 1024
      mv /etc/dkim/mail.private "$domain_key"
      mv /etc/dkim/mail.txt "/etc/dkim/${domain}.mail.txt"
    }
  done

  # fix DKIM keys permissions
  chown _rspamd /etc/dkim/*.mail.key
  chmod 400 /etc/dkim/*.mail.key

  [ ! -e /var/log/rspamd ] || chown -R _rspamd:_rspamd /var/log/rspamd

  regen_conf_files=$1
  [ -z "$regen_conf_files" ] && exit 0

  # compile sieve script
  [[ "$regen_conf_files" =~ rspamd\.sieve ]] && {
    sievec /etc/dovecot/global_script/rspamd.sieve
    chown -R vmail:mail /etc/dovecot/global_script
    systemctl restart dovecot
  }

  # Restart rspamd due to the upgrade
  # https://rspamd.com/announce/2016/08/01/rspamd-1.3.1.html 
  systemctl -q restart rspamd.service 
}

FORCE=${2:-0}
DRY_RUN=${3:-0}

case "$1" in
  pre)
    do_pre_regen $4
    ;;
  post)
    do_post_regen $4
    ;;
  *)
    echo "hook called with unknown argument \`$1'" >&2
    exit 1
    ;;
esac

exit 0
