#!/usr/bin/env bash
set -euo pipefail

SERVICE_NAME="vmess-domain-rotator"
REMOVE_AUTH_FILES="1"

usage() {
	cat <<'EOF'
Usage: sudo bash scripts/uninstall_debian.sh

This script will:
- Stop and disable the systemd timer and service
- Remove systemd unit files
- Remove environment/auth files created by installer (default)
- Keep your git repository and all files intact

Options:
 --service-name <name> Service base name (default: vmess-domain-rotator)
 --keep-auth-files     Keep /etc/<service>.env and /var/lib/<service>
 -h, --help            Show help

Examples:
 sudo bash scripts/uninstall_debian.sh
 sudo bash scripts/uninstall_debian.sh --keep-auth-files
EOF
}

while [[ $# -gt 0 ]]; do
	case "$1" in
		--service-name)
			SERVICE_NAME="$2"
			shift 2
			;;
		--keep-auth-files)
			REMOVE_AUTH_FILES="0"
			shift
			;;
		-h|--help)
			usage
			exit 0
			;;
		*)
			echo "Unknown option: $1" >&2
			usage
			exit 1
			;;
	esac
done

if [[ "$(id -u)" -ne 0 ]]; then
	echo "Please run as root (use sudo)." >&2
	exit 1
fi

ENV_FILE="/etc/${SERVICE_NAME}.env"
STATE_DIR="/var/lib/${SERVICE_NAME}"

# Stop and disable timer
if systemctl list-unit-files | grep -q "^${SERVICE_NAME}.timer"; then
	echo "Stopping and disabling ${SERVICE_NAME}.timer..."
	systemctl disable --now "${SERVICE_NAME}.timer" || true
fi

# Stop service if running
if systemctl list-unit-files | grep -q "^${SERVICE_NAME}.service"; then
	echo "Stopping ${SERVICE_NAME}.service..."
	systemctl stop "${SERVICE_NAME}.service" || true
fi

# Remove systemd unit files
echo "Removing systemd unit files..."
rm -f "/etc/systemd/system/${SERVICE_NAME}.service"
rm -f "/etc/systemd/system/${SERVICE_NAME}.timer"

if [[ "$REMOVE_AUTH_FILES" == "1" ]]; then
	echo "Removing auth/env files..."
	rm -f "$ENV_FILE"
	rm -rf "$STATE_DIR"
fi

systemctl daemon-reload
systemctl reset-failed

echo ""
echo "✓ Uninstall complete!"
echo ""
if [[ "$REMOVE_AUTH_FILES" == "1" ]]; then
	echo "Note: Service env/auth files have been removed."
else
	echo "Note: Service env/auth files were kept."
fi
echo "      Your git repository and project files have been preserved."
echo ""