#!/bin/sh
set -eu
trap '' HUP

VERSION="298"
SERVER=""
PREV=""
for ARG in "$@"; do
  if [ "$PREV" = "server" ]; then SERVER=${ARG%/}; break; fi
  case "$ARG" in -s|--server) PREV="server" ;; *) PREV="" ;; esac
done
[ -n "$SERVER" ] || { echo '[Offseek] 缺少平台地址。' >&2; exit 1; }

as_root() {
  if [ "$(id -u)" -eq 0 ]; then "$@"; elif command -v sudo >/dev/null 2>&1; then sudo "$@"; else return 1; fi
}

install_bash() {
  command -v bash >/dev/null 2>&1 && return 0
  echo '[Offseek] 当前系统缺少 bash，正在安装兼容运行环境……' >&2
  if command -v apt-get >/dev/null 2>&1; then
    as_root apt-get update -qq || true
    as_root env DEBIAN_FRONTEND=noninteractive apt-get install -y bash ca-certificates
  elif command -v dnf >/dev/null 2>&1; then as_root dnf install -y bash ca-certificates
  elif command -v microdnf >/dev/null 2>&1; then as_root microdnf install -y bash ca-certificates
  elif command -v yum >/dev/null 2>&1; then as_root yum install -y bash ca-certificates
  elif command -v apk >/dev/null 2>&1; then as_root apk add --no-cache bash ca-certificates
  elif command -v pacman >/dev/null 2>&1; then as_root pacman -Sy --noconfirm bash ca-certificates
  elif command -v zypper >/dev/null 2>&1; then as_root zypper --non-interactive install bash ca-certificates
  elif command -v xbps-install >/dev/null 2>&1; then as_root xbps-install -Sy bash ca-certificates
  else
    echo '[Offseek] 无法识别包管理器，请先安装 bash。' >&2
    return 1
  fi
  command -v bash >/dev/null 2>&1
}

install_bash || exit 1
TMP="$(mktemp "${TMPDIR:-/tmp}/offseek-test.XXXXXX")"
trap 'rm -f "$TMP"' EXIT INT TERM
curl -fL --retry 3 --retry-delay 2 --connect-timeout 15 --max-time 90 \
  "$SERVER/install.sh?v=$VERSION" -o "$TMP"
chmod 700 "$TMP"
bash "$TMP" "$@"
