# Install, upgrade and removal steps of the AntiFind service. systemd is only
# touched when it is running (not in a chroot or a container build).

_systemd_running() {
  [ -d /run/systemd/system ]
}

post_install() {
  if _systemd_running; then
    systemctl daemon-reload >/dev/null 2>&1 || true
    systemctl enable --now antifindd.service >/dev/null 2>&1 || true
    for _ in 1 2 3 4 5 6 7 8 9 10; do systemctl is-active --quiet antifindd.service && break; sleep 1; done
    if systemctl is-active --quiet antifindd.service; then
      echo ">>> The AntiFind service is running; it starts with the system and is restarted if it fails."
    else
      echo ">>> The AntiFind service is NOT running. Start it with: sudo systemctl enable --now antifindd (journalctl -u antifindd says why)."
    fi
  else
    echo ">>> Start the AntiFind service with: systemctl enable --now antifindd"
  fi
  echo ">>> Then search with: antifind <name>"
}

post_upgrade() {
  if _systemd_running; then
    systemctl daemon-reload >/dev/null 2>&1 || true
    systemctl try-restart antifindd.service >/dev/null 2>&1 || true
    systemctl is-active --quiet antifindd.service || echo ">>> The AntiFind service is NOT running after the upgrade. Start it with: sudo systemctl start antifindd"
  fi
}

pre_remove() {
  if _systemd_running; then
    systemctl disable --now antifindd.service >/dev/null 2>&1 || true
  fi
}

post_remove() {
  if _systemd_running; then
    systemctl daemon-reload >/dev/null 2>&1 || true
  fi
  # The saved index and the history are made again from the disks. The trial record and a
  # licence key stay (a reinstall does not restart the trial, and a bought licence does not have
  # to be entered again); delete /var/lib/antifind by hand to remove them too.
  if [ -d /var/lib/antifind ]; then
    find /var/lib/antifind -mindepth 1 ! -name trial.rec ! -name licence.key -delete 2>/dev/null || true
  fi
}
