#!/bin/bash
# Auto-fix line endings if needed
if [[ -n $(file "$0" | grep -i "crlf") ]]; then
    echo "Fixing line endings..."
    TEMP_FILE=$(mktemp)
    tr -d '\r' < "$0" > "$TEMP_FILE"
    mv "$TEMP_FILE" "$0"
    chmod +x "$0"
    exec "$0" "$@"
fi

# Ubuntu VPN Gateway Setup with Load Balancing
# This script configures Ubuntu to route all traffic through MikroTik tunnels

set -e

# Color codes
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m'

# Check root
if [[ $EUID -ne 0 ]]; then
   echo -e "${RED}Please run as root${NC}"
   exit 1
fi

echo -e "${GREEN}=== Ubuntu VPN Gateway Setup ===${NC}"
echo ""

# Step 1: Backup current configuration
echo -e "${YELLOW}Creating backup...${NC}"
mkdir -p /root/network-backup
ip route save > /root/network-backup/routes.backup
iptables-save > /root/network-backup/iptables.backup
cp /etc/sysctl.conf /root/network-backup/sysctl.backup 2>/dev/null || true
cp /etc/systemd/resolved.conf /root/network-backup/resolved.conf.backup 2>/dev/null || true
echo -e "${GREEN}✓ Backup created${NC}"

# Step 2: Enable IP forwarding
echo -e "${YELLOW}Enabling IP forwarding...${NC}"
cat > /etc/sysctl.d/99-tunnel.conf << EOF
net.ipv4.ip_forward=1
net.ipv6.conf.all.forwarding=1
EOF
sysctl -p /etc/sysctl.d/99-tunnel.conf
echo -e "${GREEN}✓ IP forwarding enabled${NC}"

# Step 3: Configure DNS using systemd-resolved
echo -e "${YELLOW}Configuring DNS...${NC}"

# Edit the systemd-resolved DNS Configuration
cat > /etc/systemd/resolved.conf << EOF
[Resolve]
DNS=8.8.8.8
FallbackDNS=8.8.4.4
Domains=~.
EOF

# Restart the systemd-resolved Service
systemctl restart systemd-resolved

# Wait a moment for the service to restart
sleep 2

# Verify DNS configuration
echo -e "${GREEN}✓ DNS configured to use Google DNS (8.8.8.8)${NC}"
echo -e "${YELLOW}Verifying DNS status:${NC}"
resolvectl status | grep "DNS Servers" || true

# Step 4: Detect VPC interface automatically
echo -e "${YELLOW}Detecting VPC interface...${NC}"
VPC_INTERFACE=$(ip -o addr show | grep "172.16.66" | awk '{print $2}' | head -n1)
if [ -z "$VPC_INTERFACE" ]; then
    echo -e "${RED}Error: Could not detect VPC interface with 172.16.66.x IP${NC}"
    exit 1
fi
echo -e "${GREEN}✓ Detected VPC interface: $VPC_INTERFACE${NC}"

# Get VPC IP address
VPC_IP=$(ip -o addr show $VPC_INTERFACE | grep -oP '172\.16\.66\.\d+' | head -n1)
echo -e "${GREEN}✓ VPC IP: $VPC_IP${NC}"

# Step 5: Add permanent routes
echo -e "${YELLOW}Adding permanent routes...${NC}"
# Create systemd-networkd configuration for persistent routes
mkdir -p /etc/systemd/network
cat > /etc/systemd/network/50-vpc-routes.network << EOF
[Match]
Name=$VPC_INTERFACE

[Route]
Destination=192.168.100.0/24
Gateway=172.16.66.3

[Route]
Destination=192.168.200.0/24
Gateway=172.16.66.3
EOF

# For immediate effect
ip route add 192.168.100.0/24 via 172.16.66.3 dev $VPC_INTERFACE 2>/dev/null || true
ip route add 192.168.200.0/24 via 172.16.66.3 dev $VPC_INTERFACE 2>/dev/null || true
systemctl restart systemd-networkd
echo -e "${GREEN}✓ Routes configured${NC}"

# Step 6: Create tunnel control script
echo -e "${YELLOW}Creating control script...${NC}"
cat > /usr/local/bin/tunnel-route << 'EOF'
#!/bin/bash

# Auto-detect VPC interface
VPC_INTERFACE=$(ip -o addr show | grep "172.16.66" | awk '{print $2}' | head -n1)
if [ -z "$VPC_INTERFACE" ]; then
    echo "Error: Could not detect VPC interface"
    exit 1
fi

case "$1" in
    enable)
        echo "Enabling tunnel routing with load balancing..."
        echo "Using VPC interface: $VPC_INTERFACE"
        # Remove existing default routes
        ip route del default 2>/dev/null || true
        # Add load-balanced routing
        ip route add default nexthop via 172.16.66.3 dev $VPC_INTERFACE weight 1
        # Keep management access through original public interface
        PUBLIC_IP=$(ip -o addr show eth0 | grep -oP 'inet \K[0-9.]+' | grep -v '127.0.0.1' | head -1)
        ip route add 91.206.171.0/24 dev eth0 src $PUBLIC_IP
        ip route add default via 91.206.171.1 dev eth0 metric 100
        echo "✓ Tunnel routing enabled"
        echo "Testing connection..."
        curl -s http://ip.webdade.com | grep -oP '(?<=IPv4 address: )\S+' || echo "Test failed"
        ;;
    disable)
        echo "Disabling tunnel routing..."
        ip route del default via 172.16.66.3 2>/dev/null || true
        ip route del default via 91.206.171.1 2>/dev/null || true
        ip route add default via 91.206.171.1 dev eth0
        echo "✓ Tunnel routing disabled"
        ;;
    status)
        echo "=== Routing Status ==="
        echo "VPC Interface: $VPC_INTERFACE"
        echo "Default routes:"
        ip route | grep default
        echo ""
        echo "DNS Configuration:"
        resolvectl status | grep -E "(DNS Servers|DNS Domain)" || systemd-resolve --status | grep -E "(DNS Servers|DNS Domain)"
        echo ""
        echo "Current external IP:"
        curl -s http://ip.webdade.com | grep -oP '(?<=IPv4 address: )\S+' || echo "Cannot determine"
        echo ""
        echo "Tunnel connectivity:"
        ping -c 1 -W 1 192.168.200.1 > /dev/null 2>&1 && echo "Primary (bonding-eoipv6): ✓ OK" || echo "Primary (bonding-eoipv6): ✗ FAIL"
        ping -c 1 -W 1 192.168.100.1 > /dev/null 2>&1 && echo "Backup (bonding-eoip): ✓ OK" || echo "Backup (bonding-eoip): ✗ FAIL"
        echo ""
        echo "Active route:"
        ip route get 8.8.8.8 | grep -oP 'via \K[^ ]+'
        ;;
    test)
        echo "=== Testing Failover ==="
        echo "Current active route:"
        ip route get 8.8.8.8 | grep -oP 'via \K[^ ]+'
        echo ""
        echo "DNS resolution test:"
        nslookup google.com | grep -A1 "Name:" || echo "DNS resolution failed"
        echo ""
        echo "DNS servers in use:"
        resolvectl status | grep "DNS Servers" || true
        echo ""
        echo "To test failover, temporarily disable primary in MikroTik:"
        echo "  /interface disable bonding-eoipv6"
        echo "  # Wait a moment, then test connectivity"
        echo "  # Traffic should now go through backup (bonding-eoip)"
        echo "  /interface enable bonding-eoipv6"
        echo "  # Traffic returns to primary"
        ;;
    *)
        echo "Usage: tunnel-route {enable|disable|status|test}"
        exit 1
        ;;
esac
EOF

chmod +x /usr/local/bin/tunnel-route
echo -e "${GREEN}✓ Control script created${NC}"

# Step 7: Create systemd service
echo -e "${YELLOW}Creating systemd service...${NC}"
cat > /etc/systemd/system/tunnel-routing.service << EOF
[Unit]
Description=VPN Gateway Tunnel Routing
After=network-online.target
Wants=network-online.target

[Service]
Type=oneshot
RemainAfterExit=yes
ExecStart=/usr/local/bin/tunnel-route enable
ExecStop=/usr/local/bin/tunnel-route disable

[Install]
WantedBy=multi-user.target
EOF

systemctl daemon-reload
echo -e "${GREEN}✓ Service created${NC}"

# Step 8: Create monitoring script
echo -e "${YELLOW}Creating monitoring script...${NC}"
cat > /usr/local/bin/tunnel-monitor << 'EOF'
#!/bin/bash

# Auto-detect VPC interface
VPC_INTERFACE=$(ip -o addr show | grep "172.16.66" | awk '{print $2}' | head -n1)

while true; do
    clear
    echo "=== VPN Gateway Monitor ==="
    echo "Time: $(date)"
    echo "VPC Interface: $VPC_INTERFACE"
    echo -n "DNS: "
    resolvectl status 2>/dev/null | grep -oP 'DNS Servers: \K[^\n]+' | head -1 || echo "Unable to determine"
    echo ""
    
    # External IP
    echo -n "Current External IP: "
    curl -s --max-time 3 http://ip.webdade.com | grep -oP '(?<=IPv4 address: )\S+' || echo "Error"
    echo ""
    
    # Tunnel Status
    echo "Tunnel Status:"
    ping -c 1 -W 1 192.168.200.1 > /dev/null 2>&1 && echo "  Primary (bonding-eoipv6): ✓ Active" || echo "  Primary (bonding-eoipv6): ✗ Down"
    ping -c 1 -W 1 192.168.100.1 > /dev/null 2>&1 && echo "  Backup (bonding-eoip): ✓ Ready" || echo "  Backup (bonding-eoip): ✗ Down"
    echo ""
    
    # Traffic stats
    echo "Interface Statistics:"
    if [ ! -z "$VPC_INTERFACE" ]; then
        echo "  $VPC_INTERFACE (to MikroTik):"
        echo -n "    TX: "; ifconfig $VPC_INTERFACE 2>/dev/null | grep -oP 'TX packets \K[0-9]+' || echo "N/A"
        echo -n "    RX: "; ifconfig $VPC_INTERFACE 2>/dev/null | grep -oP 'RX packets \K[0-9]+' || echo "N/A"
    fi
    
    sleep 5
done
EOF

chmod +x /usr/local/bin/tunnel-monitor
echo -e "${GREEN}✓ Monitor script created${NC}"

# Step 9: Create restore script
cat > /root/restore-network.sh << 'EOF'
#!/bin/bash
echo "Restoring original network configuration..."
systemctl stop tunnel-routing.service 2>/dev/null || true
systemctl disable tunnel-routing.service 2>/dev/null || true
tunnel-route disable
ip route flush all
ip route restore < /root/network-backup/routes.backup
iptables-restore < /root/network-backup/iptables.backup
rm -f /etc/sysctl.d/99-tunnel.conf
rm -rf /etc/systemd/network/50-vpc-routes.network
# Restore DNS configuration
cp /root/network-backup/resolved.conf.backup /etc/systemd/resolved.conf 2>/dev/null || true
systemctl restart systemd-resolved
systemctl restart systemd-networkd
sysctl -p
echo "Network configuration restored!"
EOF
chmod +x /root/restore-network.sh

echo ""
echo -e "${GREEN}=== Setup Complete ===${NC}"
echo ""
echo "✓ IP Forwarding: Enabled"
echo "✓ DNS: Set to Google DNS (8.8.8.8)"
echo "✓ Routes: Configured to use tunnels"
echo "✓ Scripts: Installed and ready"
echo ""
echo "Available commands:"
echo -e "  ${YELLOW}tunnel-route enable${NC}    - Enable tunnel routing"
echo -e "  ${YELLOW}tunnel-route disable${NC}   - Disable tunnel routing"
echo -e "  ${YELLOW}tunnel-route status${NC}    - Check status"
echo -e "  ${YELLOW}tunnel-route test${NC}      - Test failover mechanism"
echo -e "  ${YELLOW}tunnel-monitor${NC}         - Real-time monitoring"
echo -e "  ${YELLOW}resolvectl status${NC}      - Check DNS configuration"
echo ""
echo "To make permanent (auto-start on boot):"
echo -e "  ${YELLOW}systemctl enable --now tunnel-routing.service${NC}"
echo ""
echo "To restore original network:"
echo -e "  ${YELLOW}/root/restore-network.sh${NC}"