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

REPO="amirhosein2004/proxy-pilot"
VERSION="${PROXY_PILOT_VERSION:-latest}"
BIN_PATH="/usr/local/bin/proxy-pilot"
CONFIG_DIR="/etc/proxy-pilot"
CONFIG_PATH="${CONFIG_DIR}/config.yaml"
SERVICE_PATH="/etc/systemd/system/proxy-pilot.service"

if [[ "$(id -u)" -ne 0 ]]; then
  echo "Error: please run this installer with sudo or as root." >&2
  exit 1
fi

ARCH="$(uname -m)"
case "${ARCH}" in
  x86_64|amd64)   ASSET_ARCH="amd64" ;;
  aarch64|arm64)  ASSET_ARCH="arm64" ;;
  *)
    echo "Error: unsupported architecture '${ARCH}' (supported: amd64, arm64)." >&2
    exit 1
    ;;
esac

ASSET_NAME="proxy-pilot-linux-${ASSET_ARCH}"
if [[ "${VERSION}" == "latest" ]]; then
  BASE_URL="https://github.com/${REPO}/releases/latest/download"
else
  BASE_URL="https://github.com/${REPO}/releases/download/${VERSION}"
fi

TMP_DIR="$(mktemp -d)"
trap 'rm -rf "${TMP_DIR}"' EXIT

echo "==> Downloading ${ASSET_NAME} (${VERSION})..."
curl -fsSL -o "${TMP_DIR}/${ASSET_NAME}" "${BASE_URL}/${ASSET_NAME}"
curl -fsSL -o "${TMP_DIR}/${ASSET_NAME}.sha256" "${BASE_URL}/${ASSET_NAME}.sha256"

echo "==> Verifying SHA-256 checksum..."
(cd "${TMP_DIR}" && sha256sum -c "${ASSET_NAME}.sha256")
install -m 0755 "${TMP_DIR}/${ASSET_NAME}" "${BIN_PATH}"

if [[ ! -x /usr/local/bin/xray ]]; then
  echo "==> Xray not found; installing official Xray-core..."
  bash -c "$(curl -fsSL https://github.com/XTLS/Xray-install/raw/main/install-release.sh)" @ install
else
  echo "==> Xray is already installed at /usr/local/bin/xray (skipping)."
fi

mkdir -p "${CONFIG_DIR}"
if [[ ! -f "${CONFIG_PATH}" ]]; then
  echo "==> Creating default config at ${CONFIG_PATH}..."
  curl -fsSL -o "${CONFIG_PATH}" "https://raw.githubusercontent.com/${REPO}/main/config.example.yaml"
  chmod 600 "${CONFIG_PATH}"
else
  echo "==> Existing ${CONFIG_PATH} preserved."
fi

echo "==> Installing systemd unit at ${SERVICE_PATH}..."
curl -fsSL -o "${SERVICE_PATH}" "https://raw.githubusercontent.com/${REPO}/main/deploy/proxy-pilot.service"
systemctl daemon-reload
systemctl enable --now proxy-pilot

echo ""
echo "proxy-pilot installed successfully ($("${BIN_PATH}" --version))!"
echo "Next steps:"
echo "  1. Import your vless:// links:  sudo proxy-pilot import"
echo "  2. Edit Bale alerts if needed:  sudo nano ${CONFIG_PATH}"
echo "  3. Check status:                sudo proxy-pilot status"
