#!/bin/bash

set -e

_generate_config() {
  echo "domains:"
  echo "    - yunohost.local"
  for domain in $YNH_DOMAINS
  do
      # Only keep .local domains (don't keep
      [[ "$domain" =~ [^.]+\.[^.]+\.local$ ]] && echo "Subdomain $domain cannot be handled by Bonjour/Zeroconf/mDNS" >&2
      [[ "$domain" =~ ^[^.]+\.local$ ]] || continue
      echo "    - $domain"
  done

  echo "interfaces:"
  local_network_interfaces="$(ip --brief a | grep ' 10\.\| 192\.168\.' | awk '{print $1}')"
  for interface in $local_network_interfaces
  do
      echo "    - $interface"
  done
}

do_init_regen() {
   do_pre_regen
   do_post_regen /etc/systemd/system/yunomdns.service
   systemctl enable yunomdns
}

do_pre_regen() {
  pending_dir="$1"

  cd /usr/share/yunohost/templates/mdns
  mkdir -p ${pending_dir}/etc/systemd/system/
  cp yunomdns.service ${pending_dir}/etc/systemd/system/

  getent passwd mdns &>/dev/null || useradd --no-create-home --shell /usr/sbin/nologin --system --user-group mdns

  mkdir -p ${pending_dir}/etc/yunohost
  _generate_config > ${pending_dir}/etc/yunohost/mdns.yml
}

do_post_regen() {
  regen_conf_files="$1"

  chown mdns:mdns /etc/yunohost/mdns.yml

  # If we changed the systemd ynh-override conf
  if echo "$regen_conf_files" | sed 's/,/\n/g' | grep -q "^/etc/systemd/system/yunomdns.service$"
  then
      systemctl daemon-reload
  fi

  # Legacy stuff to enable the new yunomdns service on legacy systems
  if [[ -e /etc/avahi/avahi-daemon.conf ]] && grep -q 'yunohost' /etc/avahi/avahi-daemon.conf
  then
      systemctl enable yunomdns
  fi

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

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

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

exit 0
