#!/bin/bash

set -e

do_pre_regen() {
  pending_dir=$1

  cd /usr/share/yunohost/templates/metronome

  # create directories for pending conf
  metronome_dir="${pending_dir}/etc/metronome"
  metronome_conf_dir="${metronome_dir}/conf.d"
  mkdir -p "$metronome_conf_dir"

  # retrieve variables
  main_domain=$(cat /etc/yunohost/current_host)

  # install main conf file
  cat metronome.cfg.lua \
    | sed "s/{{ main_domain }}/${main_domain}/g" \
    > "${metronome_dir}/metronome.cfg.lua"

  # add domain conf files
  for domain in $YNH_DOMAINS; do
    cat domain.tpl.cfg.lua \
      | sed "s/{{ domain }}/${domain}/g" \
      > "${metronome_conf_dir}/${domain}.cfg.lua"
  done

  # remove old domain conf files
  conf_files=$(ls -1 /etc/metronome/conf.d \
                 | awk '/^[^\.]+\.[^\.]+.*\.cfg\.lua$/ { print $1 }')
  for file in $conf_files; do
    domain=${file%.cfg.lua}
    [[ $YNH_DOMAINS =~ $domain ]] \
      || touch "${metronome_conf_dir}/${file}"
  done
}

do_post_regen() {
  regen_conf_files=$1

  # retrieve variables
  main_domain=$(cat /etc/yunohost/current_host)
  
  # FIXME : small optimization to do to avoid calling a yunohost command ... 
  # maybe another env variable like YNH_MAIN_DOMAINS idk
  domain_list=$(yunohost domain list --exclude-subdomains --output-as plain --quiet)

  # create metronome directories for domains
  for domain in $domain_list; do
    mkdir -p "/var/lib/metronome/${domain//./%2e}/pep"
    # http_upload directory must be writable by metronome and readable by nginx
    mkdir -p  "/var/xmpp-upload/${domain}/upload"
    # sgid bit allows that file created in that dir will be owned by www-data
    # despite the fact that metronome ain't in the www-data group
    chmod g+s "/var/xmpp-upload/${domain}/upload"
  done

  # fix some permissions
  [ ! -e '/var/xmpp-upload' ] || chown -R metronome:www-data "/var/xmpp-upload/"
  [ ! -e '/var/xmpp-upload' ] || chmod 750 "/var/xmpp-upload/"

  # metronome should be in ssl-cert group to let it access SSL certificates
  usermod -aG ssl-cert metronome
  chown -R metronome: /var/lib/metronome/
  chown -R metronome: /etc/metronome/conf.d/

  [[ -z "$regen_conf_files" ]] \
    || systemctl restart metronome
}

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
