post_install() {
  # Remove old systemd service file if it exists (from old installation)
  if [[ -f /usr/lib/systemd/system/netsody.service ]]; then
    # Stop the old service if it's running
    if systemctl is-active netsody.service >/dev/null 2>&1; then
      systemctl stop netsody.service >/dev/null 2>&1 || true
      sleep 1
    fi
    # Remove the old service file
    rm -f /usr/lib/systemd/system/netsody.service
    systemctl daemon-reload >/dev/null 2>&1 || true
  fi

  # Create auth token only on first installation
  if [[ ! -f /etc/netsody/auth.token ]]; then
    install -d -m700 /etc/netsody
    umask 077
    TOKEN="$(openssl rand -hex 12)"
    echo "$TOKEN" > /etc/netsody/auth.token
    chmod 600 /etc/netsody/auth.token
  fi

  # Always reinstall & restart service
  if command -v netsody >/dev/null 2>&1; then
    netsody service stop >/dev/null 2>&1 || true
    netsody service uninstall >/dev/null 2>&1 || true
    netsody service install >/dev/null 2>&1 || true
    netsody service start >/dev/null 2>&1 || true
  fi

  cat <<'MSG'
An API auth token was created at: /etc/netsody/auth.token
To use Netsody, copy it into your home directory:
  mkdir -p ~/.netsody
  sudo cat /etc/netsody/auth.token > ~/.netsody/auth.token
  chmod 600 ~/.netsody/auth.token
MSG
}

post_upgrade() {
  # Same as post_install for upgrades
  post_install
}

pre_remove() {
  # Stop and uninstall service
  if command -v netsody >/dev/null 2>&1; then
    netsody service stop >/dev/null 2>&1 || true
    netsody service uninstall >/dev/null 2>&1 || true
  fi
}

post_remove() {
  echo
  echo "NOTE: ~/.netsody is not automatically removed."
  echo "If not needed anymore: rm -rf ~/.netsody"
  echo
}
