#!/bin/bash
clear
echo "============================================="
echo "    L2TP/IPSec VPN 一键安装脚本（小邹专用）  "
echo "                                             "
echo "    建议 Ubuntu22.04系统 其他版本自行测试    "
echo "============================================="

#================= 自定义账号密码 =================
VPN_USER="135492"
VPN_PASS="qq135492"
VPN_PSK="12345678"
#==================================================

NIC=$(ip route get 1.1.1.1 | awk '{print $5}' | head -1)
[ -z "$NIC" ] && NIC="eth0"

echo -e "\n自动识别网卡：$NIC"
echo -e "VPN 账号：$VPN_USER"
echo -e "VPN 密码：$VPN_PASS"
echo -e "IPSec密钥：$VPN_PSK\n"

echo "[1] 安装依赖组件..."
if [ -f /etc/redhat-release ]; then
  yum install -y xl2tpd openswan ppp iptables-services >/dev/null 2>&1
else
  apt update >/dev/null 2>&1
  apt install -y xl2tpd strongswan ppp iptables iptables-persistent >/dev/null 2>&1
fi

echo "[2] 配置 IPSec 核心参数..."
cat >/etc/ipsec.conf <<EOF
config setup
        protostack=netkey
        nat_traversal=yes
        virtual_private=%v4:10.0.0.0/8,%v4:192.168.0.0/16,%v4:172.16.0.0/12
        oe=off
        plutoopts="--debug 0"

conn L2TP-PSK
        authby=secret
        pfs=no
        auto=add
        keyingtries=3
        rekey=no
        ikelifetime=8h
        keylife=1h
        type=transport
        left=%defaultroute
        leftprotoport=17/1701
        right=%any
        rightprotoport=17/%any
        dpddelay=30
        dpdtimeout=120
        dpdaction=clear
EOF

cat >/etc/ipsec.secrets <<EOF
%any %any : PSK "$VPN_PSK"
EOF

echo "[3] 配置 XL2TPD 服务..."
cat >/etc/xl2tpd/xl2tpd.conf <<EOF
[global]
ipsec saref = yes
saref refinfo = 30
[lns default]
ip range = 192.168.23.10-192.168.23.254
local ip = 192.168.23.1
require chap = yes
refuse pap = yes
require authentication = yes
name = l2tpd
pppoptfile = /etc/ppp/options.xl2tpd
length bit = yes
EOF

cat >/etc/ppp/options.xl2tpd <<EOF
require-mschap-v2
ms-dns 8.8.8.8
ms-dns 1.1.1.1
asyncmap 0
auth
crtscts
lock
hide-password
modem
name l2tpd
proxyarp
nobsdcomp
novj
novjccomp
EOF

echo "[4] 写入账号密码配置..."
cat >/etc/ppp/chap-secrets <<EOF
$VPN_USER l2tpd $VPN_PASS *
EOF

echo "[5] 开启内核IP转发..."
sed -i 's/net.ipv4.ip_forward=0/net.ipv4.ip_forward=1/' /etc/sysctl.conf
echo "net.ipv4.ip_forward=1" >> /etc/sysctl.conf
echo "net.ipv4.ip_no_pmtu_disc=1" >> /etc/sysctl.conf
sysctl -p >/dev/null 2>&1

echo "[6] 配置防火墙转发规则..."
iptables -t nat -F
iptables -t nat -A POSTROUTING -o $NIC -j MASQUERADE
iptables -A FORWARD -p tcp --syn -s 192.168.23.0/24 -j TCPMSS --set-mss 1356
iptables -A FORWARD -s 192.168.23.0/24 -j ACCEPT
iptables -A FORWARD -d 192.168.23.0/24 -j ACCEPT
iptables -A INPUT -p udp --dport 500 -j ACCEPT
iptables -A INPUT -p udp --dport 4500 -j ACCEPT

# 关闭冲突防火墙
systemctl stop firewalld >/dev/null 2>&1
systemctl disable firewalld >/dev/null 2>&1
ufw disable >/dev/null 2>&1

# 保存iptables规则（区分系统）
if [ -f /etc/redhat-release ]; then
  service iptables save >/dev/null 2>&1
  systemctl enable iptables >/dev/null 2>&1
else
  # Ubuntu/Debian 保存iptables规则到持久化文件
  netfilter-persistent save >/dev/null 2>&1
fi

echo "[7] 启动并自启服务..."
# 统一服务名适配（strongswan/openswan）
if [ -f /etc/redhat-release ]; then
  systemctl enable ipsec xl2tpd >/dev/null 2>&1
  systemctl restart ipsec xl2tpd >/dev/null 2>&1
else
  systemctl enable strongswan xl2tpd >/dev/null 2>&1
  systemctl restart strongswan xl2tpd >/dev/null 2>&1
fi

# 新增：创建开机自启脚本（兜底保障）
cat >/etc/rc.local <<EOF
#!/bin/bash
# 重启后重新加载iptables规则
if [ -f /etc/redhat-release ]; then
  service iptables restart >/dev/null 2>&1
else
  netfilter-persistent reload >/dev/null 2>&1
fi
# 重启VPN服务
if [ -f /etc/redhat-release ]; then
  systemctl restart ipsec xl2tpd >/dev/null 2>&1
else
  systemctl restart strongswan xl2tpd >/dev/null 2>&1
fi
EOF
# 赋予执行权限并启用rc.local
chmod +x /etc/rc.local
if [ ! -f /etc/systemd/system/rc-local.service ]; then
  cat >/etc/systemd/system/rc-local.service <<EOF
[Unit]
Description=/etc/rc.local Compatibility
ConditionPathExists=/etc/rc.local

[Service]
Type=forking
ExecStart=/etc/rc.local start
TimeoutSec=0
StandardOutput=tty
RemainAfterExit=yes
SysVStartPriority=99

[Install]
WantedBy=multi-user.target
EOF
fi
systemctl enable rc-local >/dev/null 2>&1
systemctl start rc-local >/dev/null 2>&1

# 自动获取公网IP
WANIP=$(curl -s --connect-timeout 2 ipv4.icanhazip.com || curl -s --connect-timeout 2 ip.sb)
[ -z "$WANIP" ] && WANIP="【服务器公网IP】"

echo ""
echo "============================================="
echo "安装完成！"
echo ""
echo "服务器IP：$WANIP"
echo "VPN 账号：$VPN_USER"
echo "VPN 密码：$VPN_PASS"
echo "IPSec密钥：$VPN_PSK"
echo "协议类型：L2TP/IPSec"
echo "============================================="