#!/bin/sh
set -e
if [ "$1" = configure ]; then
  if ! getent passwd yes-site >/dev/null; then
    adduser --system --group --no-create-home --home /nonexistent --shell /usr/sbin/nologin yes-site >/dev/null
  fi
  install -d -m 0750 -o root -g yes-site /etc/yes-site
  # ctg-backup (owner backup standard) integration: link the packaged config in when the tool is installed (it owns /etc/ctg-backup, 0700)
  if [ -d /etc/ctg-backup ]; then
    ln -sf /usr/share/yes-site/ctg-backup/paths /etc/ctg-backup/paths
    ln -sf /usr/share/yes-site/ctg-backup/excludes /etc/ctg-backup/excludes
    # no pre-hook since 0.9.9 (the data is in PostgreSQL, covered by pgBackRest): drop the old SQLite-snapshot hook link and its leftovers
    if [ "$(readlink /etc/ctg-backup/pre.sh 2>/dev/null)" = /usr/lib/yes-site/yes-backup-snapshot ]; then rm -f /etc/ctg-backup/pre.sh; fi
    rm -f /var/backups/yes-site/yes.db /var/backups/yes-site/yes.db.tmp /var/backups/yes-site/yes.db-wal /var/backups/yes-site/yes.db-shm; rmdir /var/backups/yes-site 2>/dev/null || true
  fi
  if [ -d /run/systemd/system ]; then
    systemctl daemon-reload || true
    systemctl enable yes-site.socket yes-site.service yes-import.timer yes-poll.service yes-cloudflared.service >/dev/null 2>&1 || true
    # socket activation: the first upgrade from a service that bound :8080 itself must stop it once so the socket can take the port
    if ! systemctl is-active --quiet yes-site.socket; then systemctl stop yes-site.service || true; systemctl start yes-site.socket || true; fi
    systemctl restart yes-site.service || true
    systemctl start yes-import.timer || true
    systemctl restart yes-poll.service || true # near-real-time new-video poller (cheap to restart: only newest pages, state is in memory)
    systemctl start yes-cloudflared.service >/dev/null 2>&1 || true
  fi
fi
exit 0
