#!/bin/sh
set -e

echo "======================================"
echo "  Alpine Soga 一键安装脚本"
echo "  支持 amd64 / arm64"
echo "======================================"

### 基础路径
SOGA_BASE="/opt/soga"
CONF_DIR="/etc/soga"
CONF_FILE="/etc/soga/soga.conf"
LOG_FILE="/var/log/soga.log"

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

### 架构识别
UNAME_ARCH="$(uname -m)"
case "$UNAME_ARCH" in
  x86_64|amd64)
    ARCH="amd64"
    SOGA_PKG="musl"
    ;;
  aarch64|arm64)
    ARCH="arm64"
    SOGA_PKG="glibc"
    ;;
  *)
    echo "❌ 不支持的架构: $UNAME_ARCH"
    exit 1
    ;;
esac

echo "👉 架构检测: $ARCH ($SOGA_PKG)"

### 安装依赖
echo "👉 安装依赖"
apk add --no-cache \
  curl wget tar bash tzdata ca-certificates >/dev/null

# arm64 需要 glibc 兼容
if [ "$ARCH" = "arm64" ]; then
  apk add --no-cache gcompat >/dev/null
fi

### 设置时区
ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime

### 创建目录
mkdir -p "$SOGA_BASE" "$CONF_DIR"
cd "$SOGA_BASE"

### 下载 Soga
if [ "$ARCH" = "amd64" ]; then
  SOGA_URL="https://github.com/vaxilu/soga/releases/latest/download/soga-linux-musl-amd64.tar.gz"
else
  SOGA_URL="https://github.com/vaxilu/soga/releases/latest/download/soga-linux-arm64.tar.gz"
fi

if [ ! -f "$SOGA_BASE/soga/soga" ]; then
  echo "👉 下载 Soga"
  wget -O soga.tar.gz "$SOGA_URL"
  tar zxvf soga.tar.gz >/dev/null
  chmod +x "$SOGA_BASE/soga/soga"
  rm -f soga.tar.gz
else
  echo "👉 已检测到 Soga，跳过下载"
fi

SOGA_BIN="$SOGA_BASE/soga/soga"

### 显示版本
echo "👉 Soga 版本:"
"$SOGA_BIN" -v || true

### 创建全局命令
ln -sf "$SOGA_BIN" /usr/bin/soga

### 确保配置文件存在（不覆盖）
if [ ! -f "$CONF_FILE" ]; then
  echo "⚠️ 未检测到 soga.conf，仅创建空文件"
  touch "$CONF_FILE"
fi

### 创建 OpenRC 服务
if [ ! -f /etc/init.d/soga ]; then
  echo "👉 创建 OpenRC 服务"
  cat > /etc/init.d/soga <<EOF
#!/sbin/openrc-run

name="soga"
description="Soga Service"
command="$SOGA_BIN"
command_args="run -c /etc/soga/soga.conf"
command_background="yes"
pidfile="/run/soga.pid"
output_log="$LOG_FILE"
error_log="$LOG_FILE"

depend() {
  need net
}
EOF

  chmod +x /etc/init.d/soga
  rc-update add soga default >/dev/null
fi

### 启动 / 重启
echo "👉 启动 Soga 服务"
if rc-service soga status >/dev/null 2>&1; then
  rc-service soga restart
else
  rc-service soga start
fi

echo "======================================"
echo "✅ Soga 安装并启动完成"
echo "--------------------------------------"
echo "📁 程序目录: $SOGA_BASE/soga"
echo "📄 配置文件: $CONF_FILE"
echo "📜 日志文件: $LOG_FILE"
echo "👉 管理命令:"
echo "   soga -v"
echo "   rc-service soga status"
echo "   rc-service soga restart"
echo "======================================"
