#!/bin/bash

set -e

echo "[1/7] Updating system..."
sudo apt update

echo "[2/7] Installing dependencies..."
sudo apt install -y build-essential gcc make libreadline-dev libssl-dev libncurses-dev zlib1g-dev wget

echo "[3/7] Downloading SoftEther..."
wget https://github.com/SoftEtherVPN/SoftEtherVPN_Stable/releases/download/v4.44-9807-rtm/softether-vpnserver-v4.44-9807-rtm-2025.04.16-linux-x64-64bit.tar.gz

echo "[4/7] Extracting..."
tar xzf softether-vpnserver-*.tar.gz

cd vpnserver || exit

echo "[5/7] Compiling (auto accept license)..."
yes 1 | make

cd .. || exit

echo "[6/7] Installing..."
sudo mv vpnserver /usr/local/
cd /usr/local/vpnserver || exit

sudo chmod 600 *
sudo chmod 700 vpnserver vpncmd

echo "[7/7] Creating systemd service..."

sudo tee /etc/systemd/system/vpnserver.service > /dev/null <<EOF
[Unit]
Description=SoftEther VPN Server
After=network.target

[Service]
Type=forking
ExecStart=/usr/local/vpnserver/vpnserver start
ExecStop=/usr/local/vpnserver/vpnserver stop
Restart=always

[Install]
WantedBy=multi-user.target
EOF

echo "[+] Reloading systemd..."
sudo systemctl daemon-reload

echo "[+] Enabling service..."
sudo systemctl enable vpnserver

echo "[+] Starting service..."
sudo systemctl start vpnserver

echo "[?] SoftEther VPN installed and running!"

echo "for windows client or it supported enter this line below"
echo "redirect-gateway def1 /n dhcp-option-DNS 1.1.1.1 /n dhcp-option-DNS 1.0.0.1 /n block-outside-dns "