#!/bin/sh
# xpasswall network installer (Linux, systemd)
# Downloads the release package for this platform from the release server,
# installs the binary and enables auto-start via systemd.
# Usage:
#   sudo ./install.sh                 # install default version (v1.3.1-rc)
#   sudo ./install.sh -v v1.3.0-rc    # install specific version
#   sudo ./install.sh --remove        # uninstall (stop+disable service, keep data)
# Env overrides: VERSION, BASE (release server base URL), PREFIX
# ASCII-only file (CJK may break on non-UTF8 locales).
set -e

VERSION="${VERSION:-v1.3.1-rc}"
BASE="${BASE:-https://www.xuanlove.download/XPassWall}"
PREFIX="${PREFIX:-/usr/local/xpasswall}"
UNIT="/etc/systemd/system/xpasswall.service"
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
WORK="$(mktemp -d)"
trap 'rm -rf "$WORK"' EXIT

info() { printf '[xpasswall] %s\n' "$*"; }
warn() { printf '[xpasswall] %s\n' "$*" 1>&2; }
die()  { printf '[xpasswall] %s\n' "$*" 1>&2; exit 1; }

need_root() {
  [ "$(id -u)" -eq 0 ] || die "Please run as root: sudo ./install.sh"
}

MODE="install"
while [ "$#" -gt 0 ]; do
  case "$1" in
    -v|--version) VERSION="$2"; shift 2 ;;
    --remove|uninstall) MODE="remove"; shift ;;
    *) die "unknown arg: $1 (see header)" ;;
  esac
done

# ---- uninstall ----
if [ "$MODE" = "remove" ]; then
  need_root
  if systemctl list-unit-files 2>/dev/null | grep -q '^xpasswall.service'; then
    systemctl stop xpasswall 2>/dev/null || true
    systemctl disable xpasswall 2>/dev/null || true
  fi
  rm -f "$UNIT"
  systemctl daemon-reload 2>/dev/null || true
  warn "Stopped and disabled xpasswall service."
  warn "Data dir kept at $PREFIX/data (remove manually with: rm -rf $PREFIX)"
  exit 0
fi

need_root

# ---- local binary fast path (offline) ----
BIN_SRC=""
for c in "$SCRIPT_DIR/xpasswall" "$SCRIPT_DIR/../xpasswall"; do
  if [ -f "$c" ]; then BIN_SRC="$c"; break; fi
done

if [ -n "$BIN_SRC" ]; then
  info "using local binary: $BIN_SRC"
else
  case "$(uname -m)" in
    x86_64|amd64)              ARCH="amd64" ;;
    aarch64|arm64)             ARCH="arm64" ;;
    armv7l|armv6l|armv5tel)    ARCH="arm" ;;
    mips|mipsel|mips64|mips64el) ARCH="mipsle" ;;
    *) die "unsupported arch: $(uname -m) (amd64/arm/arm64/mipsle)" ;;
  esac
  URL="$BASE/xpasswall-$VERSION-linux-$ARCH.tar.gz"
  info "downloading $URL"
  if command -v curl >/dev/null 2>&1; then
    curl -fsSL -o "$WORK/pkg.tar.gz" "$URL" || die "download failed (curl)"
  elif command -v wget >/dev/null 2>&1; then
    wget -qO "$WORK/pkg.tar.gz" "$URL" || die "download failed (wget)"
  else
    die "need curl or wget to download the release package"
  fi
  tar -xzf "$WORK/pkg.tar.gz" -C "$WORK"
  [ -f "$WORK/xpasswall" ] || die "release package broken: xpasswall binary not found"
  BIN_SRC="$WORK/xpasswall"
fi

# ---- install ----
mkdir -p "$PREFIX/data"
cp -f "$BIN_SRC" "$PREFIX/xpasswall"
chmod 755 "$PREFIX/xpasswall"
if [ -f "$WORK/xpasswall.service" ]; then
  cp -f "$WORK/xpasswall.service" "$UNIT"
fi
if [ -f "$WORK/LICENSE" ]; then
  cp -f "$WORK/LICENSE" "$PREFIX/LICENSE" 2>/dev/null || true
fi

# systemd unit: fallback default if package has none
if [ ! -f "$UNIT" ]; then
  cat > "$UNIT" <<EOF
[Unit]
Description=xpasswall proxy manager
After=network-online.target
Wants=network-online.target

[Service]
Type=simple
WorkingDirectory=$PREFIX
ExecStart=$PREFIX/xpasswall
Restart=on-failure
RestartSec=3

[Install]
WantedBy=multi-user.target
EOF
fi

systemctl daemon-reload
systemctl enable xpasswall >/dev/null 2>&1
systemctl restart xpasswall
systemctl --no-pager --lines=5 status xpasswall || true

info "Installed and auto-start enabled: $PREFIX/xpasswall"
info "Release source: $BASE (version $VERSION)"
info "Panel: http://127.0.0.1:8080"
info "Default admin: admin / admin123 (force-change on first login)"
info "Data dir: $PREFIX/data (env XPASSWALL_DATA overrides)"
info "Logs: journalctl -u xpasswall -f"
info "Uninstall: sudo $0 --remove"