#!/usr/bin/env bash
# 在 192.168.20.100 安装 Dubbo 开发代理（方案 C）

set -euo pipefail

INSTALL_DIR="${INSTALL_DIR:-/opt/dubbo-dev-proxy}"
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

echo "[1/5] 安装 socat"
if command -v yum >/dev/null 2>&1; then
  yum install -y socat
elif command -v dnf >/dev/null 2>&1; then
  dnf install -y socat
elif command -v apt-get >/dev/null 2>&1; then
  apt-get update && apt-get install -y socat
else
  echo "请手动安装 socat" >&2
  exit 1
fi

echo "[2/5] 安装脚本与配置到 ${INSTALL_DIR}"
mkdir -p "$INSTALL_DIR"
install -m 0644 "${SCRIPT_DIR}/dubbo-proxy.map" "${INSTALL_DIR}/dubbo-proxy.map"
install -m 0755 "${SCRIPT_DIR}/dubbo-proxy-refresh.sh" "${INSTALL_DIR}/dubbo-proxy-refresh.sh"
install -m 0755 "${SCRIPT_DIR}/dubbo-proxy-status.sh" "${INSTALL_DIR}/dubbo-proxy-status.sh"
install -m 0755 "${SCRIPT_DIR}/dubbo-proxy-stop.sh" "${INSTALL_DIR}/dubbo-proxy-stop.sh"

echo "[3/5] 开放防火墙端口 32080-32100（仅开发代理）"
if command -v firewall-cmd >/dev/null 2>&1 && systemctl is-active firewalld >/dev/null 2>&1; then
  firewall-cmd --permanent --add-port=32080-32100/tcp || true
  firewall-cmd --reload || true
  echo "firewalld 已开放 32080-32100/tcp"
else
  echo "未检测到 firewalld，跳过防火墙配置"
fi

echo "[4/5] 安装 systemd 服务"
cat > /etc/systemd/system/dubbo-dev-proxy.service <<EOF
[Unit]
Description=GBS Dubbo Dev Proxy Refresh
After=network-online.target
Wants=network-online.target

[Service]
Type=oneshot
ExecStart=${INSTALL_DIR}/dubbo-proxy-refresh.sh
RemainAfterExit=yes

[Install]
WantedBy=multi-user.target
EOF

cat > /etc/systemd/system/dubbo-dev-proxy.timer <<EOF
[Unit]
Description=Refresh GBS Dubbo Dev Proxy every 3 minutes

[Timer]
OnBootSec=90s
OnUnitActiveSec=180s
AccuracySec=30s
Unit=dubbo-dev-proxy.service

[Install]
WantedBy=timers.target
EOF

systemctl daemon-reload
systemctl enable dubbo-dev-proxy.service dubbo-dev-proxy.timer
systemctl start dubbo-dev-proxy.service
systemctl start dubbo-dev-proxy.timer

echo "[5/5] 首次刷新完成，查看状态："
"${INSTALL_DIR}/dubbo-proxy-status.sh"

echo
echo "安装完成。Pod 漂移后由 timer 自动刷新，也可手动执行："
echo "  ${INSTALL_DIR}/dubbo-proxy-refresh.sh"
