#!/bin/sh
set -e

_pg() {
  if command -v runuser >/dev/null 2>&1; then
    runuser -u postgres -- "$@"
  else
    su -s /bin/sh postgres -c "$*"
  fi
}

case "$1" in
configure)
  if ! getent passwd grotti >/dev/null; then
    adduser --system --group --home /var/lib/grotti --no-create-home \
      --gecos "Grotti farm manager" grotti
  fi

  mkdir -p /var/lib/grotti/data/eingang /var/lib/grotti/slice /etc/grotti
  chown -R grotti:grotti /var/lib/grotti
  chmod 750 /var/lib/grotti

  if [ ! -f /etc/grotti/config.json ]; then
    cp /usr/share/grotti/config.pi.json /etc/grotti/config.json
  fi
  chmod 640 /etc/grotti/config.json
  chown root:grotti /etc/grotti/config.json

  if getent passwd postgres >/dev/null 2>&1; then
    _pg psql -tAc "SELECT 1 FROM pg_roles WHERE rolname='grotti'" | grep -q 1 \
      || _pg createuser -D -R -S grotti || true
    _pg psql -tAc "SELECT 1 FROM pg_database WHERE datname='grotti'" | grep -q 1 \
      || _pg createdb -O grotti grotti || true
    _pg psql -c "GRANT ALL PRIVILEGES ON DATABASE grotti TO grotti;" >/dev/null 2>&1 || true
  fi

  if command -v systemctl >/dev/null 2>&1; then
    systemctl daemon-reload || true
    systemctl enable grotti.service || true
    systemctl restart grotti.service || true
  fi
  ;;
esac

exit 0
