#!/bin/bash
POSTFIX='/usr/sbin/postfix'
MONITOR_INTERVAL=10 # seconds

exec 2>&1

if [[ ! -d /state/envdir ]]; then
    mkdir -p /state/envdir
    chown mastodon:mastodon /state/envdir
fi

if [[ ! -e /state/envdir/WEB_DOMAIN ]]; then
    if [[ -n "$WEB_DOMAIN" ]]; then
        echo "$WEB_DOMAIN" > /state/envdir/WEB_DOMAIN
    else
        hostname --fqdn > /state/envdir/WEB_DOMAIN
    fi
    chown mastodon:mastodon /state/envdir/*
fi

cat /etc/postfix/main.cf | grep -v '^myhostname' > /etc/postfix/main.new
rm /etc/postfix/main.cf
echo "myhostname = $(cat /state/envdir/WEB_DOMAIN)" >> /etc/postfix/main.cf
echo "myorigin = $(cat /state/envdir/WEB_DOMAIN)" >> /etc/postfix/main.cf
cat /etc/postfix/main.new >> /etc/postfix/main.cf
rm /etc/postfix/main.new

running() {
  pkill -0 master
}

start() {
  echo "postfix starting..."
  /etc/init.d/postfix start
}

stop() {
  if running; then
    echo Stopping
    /etc/init.d/postfix stop
  fi
}

reload() {
  echo Reloading
  /etc/init.d/postfix reload
}

check() {
  echo Checking
  "$POSTFIX" check
}

status() {
  "$POSTFIX" status
}


trap 'echo INT; stop; exit' INT
trap 'echo QUIT; stop; exit' QUIT
trap 'echo TERM; stop; exit' TERM
trap 'echo STOP; stop' STOP
trap 'echo HUP; reload' HUP
trap 'echo USR1; check' USR1
trap 'echo USR2; status' USR2

while :; do
  running || start
  sleep $MONITOR_INTERVAL
done