#!/bin/sh
set -eu

BASE_URL="${REALMCTL_BASE_URL:-https://realmctl.xiaotian.de}"
INSTALL_PATH="/usr/local/bin/realmctl"

if [ "$(id -u)" != "0" ]; then
  echo "请使用 root 用户运行"
  exit 1
fi

if [ "$(uname -s)" != "Linux" ]; then
  echo "仅支持 Linux"
  exit 1
fi

if ! command -v systemctl >/dev/null 2>&1 || [ ! -d /run/systemd/system ]; then
  echo "未检测到 systemd"
  exit 1
fi

case "$(uname -m)" in
  x86_64|amd64) arch="amd64" ;;
  aarch64|arm64) arch="arm64" ;;
  armv7l|armv7*) arch="armv7" ;;
  *) echo "不支持的架构：$(uname -m)"; exit 1 ;;
esac

url="$BASE_URL/realmctl-linux-$arch"
tmp="$(mktemp)"
trap 'rm -f "$tmp"' EXIT

echo "下载 realmctl: $url"
if command -v curl >/dev/null 2>&1; then
  curl -fsSL "$url" -o "$tmp"
elif command -v wget >/dev/null 2>&1; then
  wget -qO "$tmp" "$url"
else
  echo "需要 curl 或 wget"
  exit 1
fi

chmod +x "$tmp"
mv "$tmp" "$INSTALL_PATH"
chmod +x "$INSTALL_PATH"

"$INSTALL_PATH" install
