#!/usr/bin/env bash
set -e

# Make sure the script is run with root privileges
if [ "$(id -u)" -ne 0 ]; then
  echo "Error: This script must be run as root or with sudo." >&2
  exit 1
fi

SERVICE_NAME="frpc-sshproxy.service"
SERVICE_FILE="/etc/systemd/system/${SERVICE_NAME}"
WORKDIR="/opt/frpclient_sshproxy"

echo "==> Stopping ${SERVICE_NAME} if running..."
systemctl stop "${SERVICE_NAME}" 2>/dev/null || true

echo "==> Disabling ${SERVICE_NAME}..."
systemctl disable "${SERVICE_NAME}" 2>/dev/null || true

if [ -f "${SERVICE_FILE}" ]; then
  echo "==> Removing systemd service unit ${SERVICE_FILE}..."
  rm -f "${SERVICE_FILE}"
  systemctl daemon-reload
  systemctl reset-failed "${SERVICE_NAME}" 2>/dev/null || true
fi

echo "==> Killing any remaining frpc processes..."
pkill -9 -f "${WORKDIR}/frpc" 2>/dev/null || true

if [ -d "${WORKDIR}" ]; then
  echo "==> Removing installation directory ${WORKDIR}..."
  rm -rf "${WORKDIR}"
fi

# Verification
if ! pgrep -f "${WORKDIR}/frpc" >/dev/null && [ ! -d "${WORKDIR}" ] && [ ! -f "${SERVICE_FILE}" ]; then
  echo "==> [SUCCESS] frpclient (ssh proxy) has been completely and cleanly uninstalled."
else
  echo "==> [WARNING] Some files or processes may still remain. Please check manually." >&2
  exit 1
fi
