#!/system/bin/sh
set -eu

try_run() {
    set +e
    "$@" >/dev/null 2>&1
    code=$?
    set -e
    return $code
}

set_http_proxy() {
    host="$1"
    port="$2"
    proxy="$host:$port"

    # 方法 1: su2 heredoc (光速虚拟机，HarukiProxy 同款)
    if command -v su2 >/dev/null 2>&1; then
        set +e
        su2 <<PROXY_CMD
settings put global http_proxy $proxy
PROXY_CMD
        code=$?
        set -e
        if [ $code -eq 0 ]; then return 0; fi
    fi

    # 方法 2: /system/bin/settings (标准 Android)
    if [ -x /system/bin/settings ]; then
        if try_run /system/bin/settings put global http_proxy "$proxy"; then
            return 0
        fi
    fi

    # 方法 3: /system/bin/cmd
    if [ -x /system/bin/cmd ]; then
        if try_run /system/bin/cmd settings put global http_proxy "$proxy"; then
            return 0
        fi
    fi

    # 方法 4: /system/bin/content
    if [ -x /system/bin/content ]; then
        if try_run /system/bin/content insert --uri content://settings/global --bind name:s:http_proxy --bind value:s:"$proxy"; then
            return 0
        fi
        if try_run /system/bin/content update --uri content://settings/global --where "name='http_proxy'" --bind value:s:"$proxy"; then
            return 0
        fi
    fi

    return 1
}

prepare_dns() {
    DNS_FILE="/etc/resolv.conf"
    TMP_DNS="$ROOT_DIR/resolv.conf"

    set +e
    awk '
        /^dns_servers:/ {flag=1; next}
        flag && /^[^[:space:]-]/ {flag=0}
        flag && /^[[:space:]]*-[[:space:]]*/ {
            line=$0
            sub(/^[[:space:]]*-[[:space:]]*/, "", line)
            gsub(/"/, "", line)
            sub(/:[0-9]+$/, "", line)
            print "nameserver " line
        }
    ' "$CONFIG_PATH" > "$TMP_DNS"
    if [ ! -s "$TMP_DNS" ]; then
        printf 'nameserver 223.5.5.5\nnameserver 1.1.1.1\n' > "$TMP_DNS"
    fi

    cp "$TMP_DNS" "$DNS_FILE" >/dev/null 2>&1
    code=$?
    set -e
    return $code
}

# ---- Root 提权 ----
# 优先尝试 su2 (光速虚拟机专用)，再回退到 su
if [ "$(id -u)" -ne 0 ]; then
    if command -v su2 >/dev/null 2>&1; then
        exec su2 -c "$0 $*"
    fi
    if command -v su >/dev/null 2>&1; then
        exec su -c "$0 $*"
    fi
    echo "需要 Root 权限才能启动 mysekaiproxy"
    exit 1
fi

ROOT_DIR="/data/local/tmp/mysekaiproxy"
BIN_NAME="mysekaiproxy-android-arm64"
BIN_PATH="$ROOT_DIR/$BIN_NAME"
CONFIG_PATH="$ROOT_DIR/config-android.yaml"
LOG_DIR="$ROOT_DIR/logs"
SYSTEM_CACERTS_DIR="/system/etc/security/cacerts"

mkdir -p "$ROOT_DIR" "$LOG_DIR" "$ROOT_DIR/cert"

if [ ! -f "$CONFIG_PATH" ]; then
    echo "未找到配置文件：$CONFIG_PATH"
    exit 1
fi

if [ ! -f "$BIN_PATH" ]; then
    echo "未找到二进制文件：$BIN_PATH"
    exit 1
fi

chmod 755 "$BIN_PATH"

eval "$($BIN_PATH ensure-ca --config "$CONFIG_PATH")"

if [ -n "${ANDROID_HASH_NAME:-}" ] && [ -f "${ANDROID_HASH_PATH:-}" ]; then
    mount -o remount,rw /system >/dev/null 2>&1 || true
    cp "$ANDROID_HASH_PATH" "$SYSTEM_CACERTS_DIR/$ANDROID_HASH_NAME"
    chmod 644 "$SYSTEM_CACERTS_DIR/$ANDROID_HASH_NAME"
fi

LISTEN="$(sed -n 's/^listen:[[:space:]]*"\{0,1\}\([^"#]*\)"\{0,1\}$/\1/p' "$CONFIG_PATH" | head -n 1)"
PROXY_IP="$(sed -n 's/^android_proxy_ip:[[:space:]]*"\{0,1\}\([^"#]*\)"\{0,1\}$/\1/p' "$CONFIG_PATH" | head -n 1)"

if [ -z "$LISTEN" ]; then
    LISTEN="0.0.0.0:8888"
fi

if [ -z "$PROXY_IP" ]; then
    PROXY_IP="127.0.0.1"
fi

PROXY_PORT="${LISTEN##*:}"

echo "[1/6] 检查 Root 权限 ... OK"
echo "[2/6] 检查二进制文件 ... OK"
echo "[3/6] 安装/更新 CA 证书 ... OK"

if prepare_dns; then
    echo "[3.5/6] 配置 DNS ... OK"
else
    echo "[3.5/6] 自动配置 DNS 失败，继续使用程序内置 DNS"
fi

if set_http_proxy "$PROXY_IP" "$PROXY_PORT"; then
    echo "[4/6] 设置系统 HTTP 代理 ... OK ($PROXY_IP:$PROXY_PORT)"
else
    echo "[4/6] Shell 层代理设置失败，交由 binary 内部自动设置"
fi

echo "[5/6] 启动 MySekaiProxy-Android (前台模式) ..."
echo "      ↳ 不要按 ◁ 退出！请按 ◯ 或 ▢ 回到桌面打开游戏。"
echo "      ↳ 停止时请执行 stop-mysekaiproxy.sh"
echo ""

# 前台运行 binary（与 HarukiProxy 行为一致）
# binary 内部会再次尝试自动发现 IP 并设置代理（双重保障）
cd "$ROOT_DIR" && exec "$BIN_PATH" serve --config "$CONFIG_PATH"
