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

SERVICE_NAME="vmess-domain-rotator"
RUN_USER=""
RUN_GROUP=""
RUN_USER_SET="0"
RUN_GROUP_SET="0"
RUN_HOME=""
INTERVAL="1h"
INSTALL_DEPS="1"
CONFIG_PATH=""
GIT_PUSH_ENABLED="1"
GIT_PUSH_REMOTE="origin"
GIT_HTTP_USERNAME="git"
GIT_HTTP_TOKEN=""
GIT_HTTP_TOKEN_FILE=""
GIT_USE_CREDENTIAL_STORE="1"
GIT_CREDENTIALS_FILE=""

usage() {
	cat <<'EOF'
Usage: sudo bash scripts/install_debian.sh [options]

Default behavior:
- Uses current git repository directory as working directory (in-place mode)
- Uses the user executing sudo as service user
- Enables git push after runtime-state commits

Options:
 --user <name>                  Service user (default: current sudo user)
 --group <name>                 Service group (default: current sudo user's group)
 --interval <value>             Timer interval, e.g. 1h/10min (default: 1h)
 --config <path>                Config file path (default: <repo>/config.server.json)
 --git-push <0|1>               Enable/disable push to remote (default: 1)
 --git-push-remote <name>       Remote name for push (default: origin)
 --git-http-username <u>        Username for HTTPS auth (default: git)
 --git-http-token <t>           HTTPS token for non-interactive push
 --git-http-token-file <f>      Read HTTPS token from file
 --git-use-credential-store <0|1> Use git credential.helper store (default: 1)
 --git-credentials-file <f>     Custom credentials file for helper store
 --no-install-deps              Skip apt dependency install
 -h, --help                     Show help

Examples:
 sudo bash scripts/install_debian.sh
 sudo bash scripts/install_debian.sh --config /opt/vmess-domain-rotator/config.server.json
 sudo bash scripts/install_debian.sh --interval 10min
 sudo bash scripts/install_debian.sh --git-push 0
 sudo bash scripts/install_debian.sh --git-http-username aurora --git-http-token-file /root/.config/vmess-token
 sudo bash scripts/install_debian.sh --git-use-credential-store 1 --git-credentials-file /home/aurora/.git-credentials
EOF
}

run_as_service_user() {
	runuser -u "$RUN_USER" -- env HOME="$RUN_HOME" "$@"
}

while [[ $# -gt 0 ]]; do
	case "$1" in
		--user)
			RUN_USER="$2"
			RUN_USER_SET="1"
			shift 2
			;;
		--group)
			RUN_GROUP="$2"
			RUN_GROUP_SET="1"
			shift 2
			;;
		--interval)
			INTERVAL="$2"
			shift 2
			;;
		--config)
			CONFIG_PATH="$2"
			shift 2
			;;
		--git-push)
			GIT_PUSH_ENABLED="$2"
			shift 2
			;;
		--git-push-remote)
			GIT_PUSH_REMOTE="$2"
			shift 2
			;;
		--git-http-username)
			GIT_HTTP_USERNAME="$2"
			shift 2
			;;
		--git-http-token)
			GIT_HTTP_TOKEN="$2"
			shift 2
			;;
		--git-http-token-file)
			GIT_HTTP_TOKEN_FILE="$2"
			shift 2
			;;
		--git-use-credential-store)
			GIT_USE_CREDENTIAL_STORE="$2"
			shift 2
			;;
		--git-credentials-file)
			GIT_CREDENTIALS_FILE="$2"
			shift 2
			;;
		--no-install-deps)
			INSTALL_DEPS="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

if ! command -v runuser >/dev/null 2>&1; then
	echo "Error: runuser is required on Debian for configuring service-user git credentials" >&2
	exit 1
fi

SOURCE_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
if ! git -C "$SOURCE_DIR" rev-parse --is-inside-work-tree >/dev/null 2>&1; then
	echo "Error: Current directory is not a git repository." >&2
	echo "This script must be run from within a git repository." >&2
	exit 1
fi
APP_DIR="$SOURCE_DIR"

if [[ -z "$CONFIG_PATH" ]]; then
	CONFIG_PATH="${APP_DIR}/config.server.json"
elif [[ "$CONFIG_PATH" != /* ]]; then
	CONFIG_PATH="${APP_DIR}/${CONFIG_PATH}"
fi

if [[ ! -r "$CONFIG_PATH" ]]; then
	echo "Error: config file not found or unreadable: $CONFIG_PATH" >&2
	exit 1
fi

if [[ -n "${SUDO_USER:-}" ]] && [[ "$RUN_USER_SET" != "1" ]]; then
	RUN_USER="$SUDO_USER"
fi

if [[ -n "${SUDO_USER:-}" ]] && [[ "$RUN_GROUP_SET" != "1" ]]; then
	RUN_GROUP="$(id -gn "$SUDO_USER")"
fi

if [[ -z "$RUN_USER" ]]; then
	echo "Error: Could not determine service user. Please run with sudo or specify --user" >&2
	exit 1
fi

if [[ -z "$RUN_GROUP" ]]; then
	echo "Error: Could not determine service group. Please run with sudo or specify --group" >&2
	exit 1
fi

if [[ ! "$GIT_PUSH_ENABLED" =~ ^[01]$ ]]; then
	echo "Error: --git-push must be 0 or 1" >&2
	exit 1
fi

if [[ ! "$GIT_USE_CREDENTIAL_STORE" =~ ^[01]$ ]]; then
	echo "Error: --git-use-credential-store must be 0 or 1" >&2
	exit 1
fi

if [[ -z "$GIT_PUSH_REMOTE" ]]; then
	echo "Error: --git-push-remote cannot be empty" >&2
	exit 1
fi

if [[ -n "$GIT_HTTP_TOKEN" ]] && [[ -n "$GIT_HTTP_TOKEN_FILE" ]]; then
	echo "Error: provide either --git-http-token or --git-http-token-file, not both" >&2
	exit 1
fi

if [[ -n "$GIT_HTTP_TOKEN_FILE" ]] && [[ ! -r "$GIT_HTTP_TOKEN_FILE" ]]; then
	echo "Error: cannot read token file: $GIT_HTTP_TOKEN_FILE" >&2
	exit 1
fi

if [[ -n "$GIT_HTTP_TOKEN_FILE" ]]; then
	GIT_HTTP_TOKEN="$(tr -d '\r\n' < "$GIT_HTTP_TOKEN_FILE")"
fi

if [[ -n "$GIT_HTTP_TOKEN" ]] && [[ -z "$GIT_HTTP_USERNAME" ]]; then
	echo "Error: --git-http-username cannot be empty when token is set" >&2
	exit 1
fi

if [[ -n "$GIT_HTTP_TOKEN" ]] && [[ "$RUN_USER" == "root" ]]; then
	echo "Error: refusing to store git token for root service user" >&2
	echo "Use --user <non-root> or disable push with --git-push 0" >&2
	exit 1
fi

RUN_HOME="$(getent passwd "$RUN_USER" | cut -d: -f6)"
if [[ -z "$RUN_HOME" ]]; then
	echo "Error: could not determine home directory for user: $RUN_USER" >&2
	exit 1
fi

if [[ "$INSTALL_DEPS" == "1" ]]; then
	export DEBIAN_FRONTEND=noninteractive
	apt-get update -y
	apt-get install -y python3 ca-certificates git
fi

RUNTIME_DIR="$(/usr/bin/python3 "${APP_DIR}/scripts/domain_updater.py" --config "$CONFIG_PATH" --print-output-settings | /usr/bin/python3 -c 'import json,sys; print(json.load(sys.stdin)["runtime_dir"])')"

mkdir -p "$RUNTIME_DIR"
chmod +x "$APP_DIR/scripts/run_update_and_commit.sh" || true
chown -R "$RUN_USER:$RUN_GROUP" "$RUNTIME_DIR"

SERVICE_STATE_DIR="/var/lib/${SERVICE_NAME}"
ENV_FILE="/etc/${SERVICE_NAME}.env"
TOKEN_FILE=""
REMOTE_URL=""
AUTH_MODE="header"

if [[ "$GIT_USE_CREDENTIAL_STORE" == "1" ]]; then
	AUTH_MODE="credential-helper-store"
fi

mkdir -p "$SERVICE_STATE_DIR"
chown "$RUN_USER:$RUN_GROUP" "$SERVICE_STATE_DIR"
chmod 750 "$SERVICE_STATE_DIR"

if [[ "$GIT_PUSH_ENABLED" == "1" ]]; then
	REMOTE_URL="$(git -C "$APP_DIR" remote get-url "$GIT_PUSH_REMOTE" 2>/dev/null || true)"
	if [[ -z "$REMOTE_URL" ]]; then
		echo "Warning: remote '$GIT_PUSH_REMOTE' not found now. Push may fail until remote is configured." >&2
	fi
fi

if [[ -n "$GIT_HTTP_TOKEN" ]]; then
	if [[ "$GIT_USE_CREDENTIAL_STORE" == "1" ]]; then
		if [[ "$REMOTE_URL" =~ ^https:// ]]; then
			helper_value="store"
			if [[ -n "$GIT_CREDENTIALS_FILE" ]]; then
				helper_value="store --file ${GIT_CREDENTIALS_FILE}"
				mkdir -p "$(dirname "$GIT_CREDENTIALS_FILE")"
				touch "$GIT_CREDENTIALS_FILE"
				chown "$RUN_USER:$RUN_GROUP" "$GIT_CREDENTIALS_FILE"
				chmod 600 "$GIT_CREDENTIALS_FILE"
			fi

			run_as_service_user git config --global credential.helper "$helper_value"
			printf 'url=%s\nusername=%s\npassword=%s\n\n' "$REMOTE_URL" "$GIT_HTTP_USERNAME" "$GIT_HTTP_TOKEN" | run_as_service_user git credential approve
		else
			echo "Warning: token provided but remote is not HTTPS; credential.helper store setup skipped." >&2
			echo "Warning: fallback to header-token-file auth mode for this install." >&2
			GIT_USE_CREDENTIAL_STORE="0"
		fi
	fi

	if [[ "$GIT_USE_CREDENTIAL_STORE" != "1" ]]; then
		TOKEN_FILE="${SERVICE_STATE_DIR}/git_http_token"
		printf '%s\n' "$GIT_HTTP_TOKEN" >"$TOKEN_FILE"
		chown "$RUN_USER:$RUN_GROUP" "$TOKEN_FILE"
		chmod 600 "$TOKEN_FILE"
		AUTH_MODE="header-token-file"
	fi
fi

run_as_service_user git config --global --add safe.directory "$APP_DIR" || true

cat >"$ENV_FILE" <<EOF
GIT_PUSH_ENABLED=${GIT_PUSH_ENABLED}
GIT_PUSH_REQUIRED=${GIT_PUSH_ENABLED}
GIT_PUSH_REMOTE=${GIT_PUSH_REMOTE}
GIT_RUNTIME_BRANCH=runtime-state
GIT_HTTP_USERNAME=${GIT_HTTP_USERNAME}
HOME=${RUN_HOME}
EOF

if [[ "$GIT_USE_CREDENTIAL_STORE" == "1" ]]; then
	if [[ -n "$GIT_CREDENTIALS_FILE" ]]; then
		printf 'GIT_CREDENTIAL_HELPER=store --file %s\n' "$GIT_CREDENTIALS_FILE" >>"$ENV_FILE"
	else
		printf 'GIT_CREDENTIAL_HELPER=store\n' >>"$ENV_FILE"
	fi
fi

if [[ -n "$TOKEN_FILE" ]]; then
	printf 'GIT_HTTP_TOKEN_FILE=%s\n' "$TOKEN_FILE" >>"$ENV_FILE"
fi

chown root:root "$ENV_FILE"
chmod 600 "$ENV_FILE"

cat >"/etc/systemd/system/${SERVICE_NAME}.service" <<EOF
[Unit]
Description=VMess Domain Rotator updater
After=network-online.target
Wants=network-online.target

[Service]
Type=oneshot
User=${RUN_USER}
Group=${RUN_GROUP}
WorkingDirectory=${APP_DIR}
EnvironmentFile=-${ENV_FILE}
UMask=0077
ExecStart=/bin/bash ${APP_DIR}/scripts/run_update_and_commit.sh ${CONFIG_PATH}
EOF

cat >"/etc/systemd/system/${SERVICE_NAME}.timer" <<EOF
[Unit]
Description=Run VMess Domain Rotator every ${INTERVAL}

[Timer]
OnBootSec=2min
OnUnitActiveSec=${INTERVAL}
AccuracySec=30s
Unit=${SERVICE_NAME}.service
Persistent=true

[Install]
WantedBy=timers.target
EOF

systemctl daemon-reload
systemctl enable --now "${SERVICE_NAME}.timer"
systemctl start "${SERVICE_NAME}.service"

echo ""
echo "✓ Installation complete!"
echo ""
echo "Configuration:"
echo "  Working directory: ${APP_DIR}"
echo "  Config path: ${CONFIG_PATH}"
echo "  Service user: ${RUN_USER}"
echo "  Service group: ${RUN_GROUP}"
echo "  Timer interval: ${INTERVAL}"
echo "  Push enabled: ${GIT_PUSH_ENABLED}"
echo "  Push remote: ${GIT_PUSH_REMOTE}"
echo "  Auth mode: ${AUTH_MODE}"
echo "  Env file: ${ENV_FILE}"
echo ""
echo "Commands:"
echo "  Check status: systemctl status ${SERVICE_NAME}.timer"
echo "  View logs:    journalctl -u ${SERVICE_NAME}.service -n 50 --no-pager"
echo "  Manual run:   sudo systemctl start ${SERVICE_NAME}.service"
echo "  Force commit: sudo -u ${RUN_USER} /bin/bash ${APP_DIR}/scripts/run_update_and_commit.sh --force-commit ${CONFIG_PATH}"
echo ""
