#!/bin/bash
# Test VPN connection to server
# Run this script after starting the VPN with: wg-quick up test-client

set -e

echo "=== VPN Connection Test ==="
echo ""

# Check if VPN interface exists
if ! ip link show test-client > /dev/null 2>&1; then
    echo "? VPN interface 'test-client' not found!"
    echo "   Start VPN with: wg-quick up test-client"
    exit 1
fi

echo "? VPN interface 'test-client' is active"
echo ""

# Check WireGuard status
echo "=== WireGuard Status ==="
sudo wg show test-client || echo "??  Warning: Cannot show WireGuard status"
echo ""

# Test ping to server VPN IP
echo "=== Testing Ping to Server VPN IP (10.8.0.1) ==="
if ping -c 3 -W 2 10.8.0.1 > /dev/null 2>&1; then
    echo "? Ping to 10.8.0.1 successful"
else
    echo "? Ping to 10.8.0.1 failed"
fi
echo ""

# Check DNS resolution
echo "=== Testing DNS Resolution ==="
if host grafana.michaelschiemer.de > /dev/null 2>&1; then
    echo "? DNS resolution works"
    host grafana.michaelschiemer.de | head -1
else
    echo "??  DNS resolution failed, but this might be OK if using VPN routing"
fi
echo ""

# Test HTTP connection to Grafana
echo "=== Testing HTTP Connection to Grafana ==="
HTTP_CODE=$(curl -s -o /dev/null -w "%{http_code}" \
    --max-time 10 \
    -H "User-Agent: Mozilla/5.0 (Linux; x86_64) AppleWebKit/537.36" \
    --insecure \
    https://grafana.michaelschiemer.de/ 2>/dev/null || echo "000")

if [ "$HTTP_CODE" = "200" ] || [ "$HTTP_CODE" = "302" ] || [ "$HTTP_CODE" = "301" ]; then
    echo "? HTTP connection successful (Status: $HTTP_CODE)"
    echo "  Traffic is reaching Grafana through VPN!"
elif [ "$HTTP_CODE" = "000" ]; then
    echo "? HTTP connection failed (could not connect)"
    echo "  Check if VPN is routing traffic correctly"
else
    echo "??  HTTP connection returned status: $HTTP_CODE"
    echo "  Connection works, but got unexpected status code"
fi
echo ""

# Check routing table
echo "=== Routing Table for VPN Network ==="
ip route show | grep "10.8.0.0/24" || echo "??  No route found for 10.8.0.0/24"
echo ""

# Check which interface is used for VPN network
echo "=== Interface Route Check ==="
ip route get 10.8.0.1 2>/dev/null || echo "??  Cannot determine route to 10.8.0.1"
echo ""

echo "=== Test Complete ==="
echo ""
echo "Next step: Run Ansible playbook to check server logs:"
echo "  cd deployment/ansible"
echo "  ansible-playbook playbooks/check-vpn-test-from-client.yml"
