#!/bin/bash
set -e

echo "===== 1. 安装 Hysteria2 ====="
bash <(curl -fsSL https://get.hy2.sh/)

echo "===== 2. 备份原有配置 ====="
if [ -f "/etc/hysteria/config.yaml" ]; then
    cp /etc/hysteria/config.yaml /etc/hysteria/config.yaml.bk.$(date +%Y%m%d_%H%M%S)
    echo "已备份旧配置文件"
fi

echo "===== 3. 写入新 config.yaml 配置 ====="
cat > /etc/hysteria/config.yaml << EOF
listen: :8090

#acme:
#  domains:
#    - 
#  email: 

tls:
  cert: /etc/hysteria/cert.pem
  key: /etc/hysteria/key.pem

auth:
  type: password
  password: MvZubHP36hxhvKDzHByr

obfs:
  type: salamander
  salamander:
    password: abcd0123xyz

masquerade:
  type: proxy
  proxy:
    url: https://bing.com/
    rewriteHost: true
EOF

echo "===== 4. 生成自签 ECDSA 证书（10年有效期） ====="
openssl req -x509 -newkey ec -pkeyopt ec_paramgen_curve:P-256 -days 3650 -nodes \
-keyout /etc/hysteria/key.pem -out /etc/hysteria/cert.pem -subj "/CN=localhost"

echo "===== 5. 修改证书文件归属用户组 ====="
chown -R hysteria:hysteria /etc/hysteria/cert.pem /etc/hysteria/key.pem

echo "===== 6. 设置开机自启并启动服务 ====="
systemctl enable --now hysteria-server

echo "===== 部署完成 ====="
echo "端口：8090"
echo "认证密码：MvZubHP36hxhvKDzHByr"
echo "混淆密码：abcd0123xyz"
echo "伪装站点：https://bing.com"
echo "查看运行状态：systemctl status hysteria-server"