#!/bin/sh
# Package-manager hooks for the TUN helper socket. The helper exits after a quiet
# minute without leases, so an active service may hold a daemon's live lease.
# Stopping the socket also stops that service (Requires=), so upgrades never stop it.
set -u
unit=meshieve-tun.socket
run_dir=/run/meshieve-tun
# A deb removed without purge reinstalls through "postinst configure <old version>",
# indistinguishable from an upgrade, so its removal records that it disabled the socket.
reenable=/var/lib/meshieve-linux/tun-socket-disabled-by-removal
booted() { [ -d /run/systemd/system ] && command -v systemctl >/dev/null 2>&1; }
leased() { booted && systemctl is-active --quiet meshieve-tun.service; }
case "${1:-}" in
  installed)
    command -v systemctl >/dev/null 2>&1 || exit 0
    if booted; then systemctl daemon-reload || true; fi
    if [ "${2:-}" = first ] || [ -e "$reenable" ]; then
      systemctl enable "$unit" >/dev/null 2>&1 || true
    fi
    rm -f "$reenable"
    rmdir "${reenable%/*}" 2>/dev/null || true
    if booted && systemctl is-enabled --quiet "$unit"; then systemctl start "$unit" || true; fi
    ;;
  check-removal)
    if leased; then
      echo 'The Meshieve TUN helper is running and may hold a live lease. Stop the mesh that uses TUN, wait a minute for the helper to exit, then retry.' >&2
      exit 1
    fi
    ;;
  removing)
    "$0" check-removal || exit 1
    command -v systemctl >/dev/null 2>&1 || exit 0
    if [ "${2:-}" = remember ] && systemctl is-enabled --quiet "$unit"; then
      mkdir -p "${reenable%/*}" && : > "$reenable"
    fi
    if booted; then systemctl stop "$unit" || true; fi
    systemctl disable "$unit" >/dev/null 2>&1 || true
    # RemoveOnStop deletes the socket node but not the directory systemd made for it.
    rmdir "$run_dir" 2>/dev/null || true
    ;;
  *)
    echo 'usage: meshieve-tun-lifecycle installed first|upgrade | check-removal | removing [remember]' >&2
    exit 2
    ;;
esac
exit 0
