#!/bin/bash

# OpenVPN Systemd Service Setup Script
# Usage: sudo ./setup-vpn-service.sh

set -e

echo "=== OpenVPN Systemd Service Setup Script ==="

# Check root privileges
if [ "$EUID" -ne 0 ]; then
    echo "Please run this script with sudo"
    exit 1
fi

# Check if OpenVPN is installed
if ! command -v openvpn &> /dev/null; then
    echo "Error: OpenVPN is not installed. Please install OpenVPN first."
    exit 1
fi

# Check if config file exists
if [ ! -f "/etc/openvpn/client/OpenVPN-Client.conf" ]; then
    echo "Error: OpenVPN configuration file does not exist"
    echo "Please ensure /etc/openvpn/client/OpenVPN-Client.conf file exists"
    exit 1
fi

# Get OpenVPN actual path
OPENVPN_PATH=$(which openvpn)
echo "Detected OpenVPN path: $OPENVPN_PATH"

# 修改配置文件，添加daemon模式
echo "Updating OpenVPN configuration for daemon mode..."
if grep -q "^daemon" /etc/openvpn/client/OpenVPN-Client.conf; then
    echo "OpenVPN already configured to run as daemon"
else
    echo "Adding daemon mode to OpenVPN configuration..."
    echo -e "\ndaemon" >> /etc/openvpn/client/OpenVPN-Client.conf
fi

# Create systemd service file with forking type
echo "Creating systemd service file..."
cat > /etc/systemd/system/openvpn-client.service << EOF
[Unit]
Description=OpenVPN Client Service
After=network.target
Wants=network.target

[Service]
Type=forking
PIDFile=/var/run/openvpn-client.pid
ExecStart=$OPENVPN_PATH --config /etc/openvpn/client/OpenVPN-Client.conf --daemon --writepid /var/run/openvpn-client.pid
WorkingDirectory=/etc/openvpn/client/
Restart=on-failure
RestartSec=5
TimeoutStartSec=30
TimeoutStopSec=30

[Install]
WantedBy=multi-user.target
EOF

echo "Service file created: /etc/systemd/system/openvpn-client.service"

# Reload systemd configuration
echo "Reloading systemd configuration..."
systemctl daemon-reload

# Enable auto-start on boot
echo "Enabling auto-start on boot..."
systemctl enable openvpn-client

# Start service in background (non-blocking)
echo "Starting OpenVPN service in background..."
systemctl start openvpn-client &
BACKGROUND_PID=$!

# 等待2秒让服务有足够时间启动，但不阻塞
echo "Waiting 2 seconds for service initialization..."
sleep 2

# 检查后台启动进程是否已完成
if wait $BACKGROUND_PID 2>/dev/null; then
    echo "OpenVPN service started successfully"
else
    echo "OpenVPN service start initiated (running in background)"
fi

# 立即检查服务状态（不等待）
echo "Quick service status check:"
if systemctl is-active --quiet openvpn-client; then
    echo "✅ OpenVPN service is active"
else
    echo "⚠️  OpenVPN service may still be starting..."
    # 再给一点时间
    sleep 1
    if systemctl is-active --quiet openvpn-client; then
        echo "✅ OpenVPN service is now active"
    else
        echo "❓ OpenVPN service status is uncertain, checking..."
        systemctl status openvpn-client --no-pager --lines=5 2>/dev/null || echo "Service status check failed"
    fi
fi

# 只显示最近3行的日志，避免过多输出
echo ""
echo "Recent service logs (last 3 lines):"
journalctl -u openvpn-client --since="1 minute ago" --no-pager --lines=3 2>/dev/null || echo "No logs available yet"

# Provide management commands
echo ""
echo "=== Service setup completed! ==="
echo "Management commands:"
echo "Start service:    systemctl start openvpn-client"
echo "Stop service:     systemctl stop openvpn-client"
echo "Restart service:  systemctl restart openvpn-client"
echo "Check status:     systemctl status openvpn-client"
echo "View logs:        journalctl -u openvpn-client -f"
echo "Disable auto-start: systemctl disable openvpn-client"

# 重要提示：VPN连接会在后台建立
echo ""
echo "Important: VPN connection will establish in the background."
echo "To check connection status, run: systemctl status openvpn-client"
echo "Or view logs: journalctl -u openvpn-client -f"
echo "To verify VPN tunnel: ip addr show tun0 2>/dev/null || echo 'Tunnel not yet established'"