#!/bin/bash
set -e

SERVER_URL="https://dbp.qzz.io/hysteria_bundle.tar.gz"
TMP_DIR="/tmp/hysteria_update"
HYSTERIA_DIR="/etc/hysteria"
CERT_DIR="/etc/letsencrypt"

echo "[*] 下载 hysteria 配置包..."
mkdir -p "$TMP_DIR"
wget -q -O "$TMP_DIR/hysteria_bundle.tar.gz" "$SERVER_URL"

echo "[*] 解压到临时目录..."
tar -xzf "$TMP_DIR/hysteria_bundle.tar.gz" -C "$TMP_DIR"

echo "[*] 更新 hysteria 配置..."
mkdir -p "$HYSTERIA_DIR"
cp -f "$TMP_DIR/etc/hysteria/config.yaml" "$HYSTERIA_DIR/config.yaml"

echo "[*] 更新证书..."
mkdir -p "$CERT_DIR"
cp -r "$TMP_DIR/etc/letsencrypt/"* "$CERT_DIR/"

echo "[*] 权限调整..."
chown -R root:root "$HYSTERIA_DIR" "$CERT_DIR"
chmod -R 600 "$CERT_DIR"/live/*/privkey.pem || true

echo "[*] 重启 hysteria 服务..."
systemctl restart hysteria-server || echo "[!] 无法自动重启，请手动检查服务"

echo "[*] 清理临时文件..."
rm -rf "$TMP_DIR"

echo "[+] 更新完成 ✅"
