#!/bin/bash
# Install QR code scanning tools for WireGuard
set -euo pipefail

echo "Installing QR code scanning tools..."

# Install zbar for QR code scanning
apt-get update
apt-get install -y zbar-tools python3-pil
apt-get clean

# Create QR code scanning script
cat >/usr/local/bin/scan-wireguard-qr.sh <<'EOF'
#!/bin/bash
# Scan WireGuard QR code and update configuration
set -euo pipefail

# Check if webcam is available
if ! ls /dev/video* >/dev/null 2>&1; then
    echo "Error: No webcam device found"
    exit 1
fi

# Create temporary file for QR data
qr_data=$(mktemp)
trap "rm -f $qr_data" EXIT

# Scan QR code
echo "Scanning QR code..."
zbarcam --raw --prescale=320x240 /dev/video0 > "$qr_data" &
zbar_pid=$!

# Wait for user to stop scanning
echo "Press Enter to stop scanning..."
read -r
kill $zbar_pid 2>/dev/null || true

# Parse QR data and update WireGuard config
if [[ -s "$qr_data" ]]; then
    # Validate QR data format (basic WireGuard format)
    if grep -q "private_key\|endpoint\|allowed_ips" "$qr_data"; then
        # Backup existing config
        if [[ -f "/etc/wireguard/wg0.conf" ]]; then
            cp /etc/wireguard/wg0.conf "/etc/wireguard/wg0.conf.bak.$(date +%Y%m%d_%H%M%S)"
        fi
        
        # Convert QR data to WireGuard config format
        python3 << 'PYTHON_EOF' "$qr_data"
import sys
import re

qr_data = sys.argv[1]

# Simple QR to WireGuard config conversion
config_lines = ["[Interface]"]
private_key = ""
address = ""

for line in open(qr_data):
    if "private_key=" in line.lower():
        private_key = line.strip()
    elif "address=" in line.lower():
        address = line.strip()

if private_key:
    config_lines.append(f"PrivateKey = {private_key.split('=')[1].strip()}")
if address:
    config_lines.append(f"Address = {address.split('=')[1].strip()}")

# Add basic peer template
config_lines.append("")
config_lines.append("[Peer]")
config_lines.append("# Add PublicKey, Endpoint, and AllowedIPs manually")

print("\n".join(config_lines))
PYTHON_EOF
        
        echo "QR code scanned successfully. Please edit /etc/wireguard/wg0.conf to complete configuration."
    else
        echo "Error: Invalid WireGuard QR code format"
        exit 1
    fi
else
    echo "Error: No QR code data captured"
    exit 1
fi
EOF

chmod +x /usr/local/bin/scan-wireguard-qr.sh

# Create desktop shortcut
mkdir -p /usr/share/applications
cat >/usr/share/applications/scan-wireguard-qr.desktop <<EOF
[Desktop Entry]
Name=Import WireGuard QR Code
Comment=Scan QR code to import WireGuard configuration
Exec=pkexec /usr/local/bin/scan-wireguard-qr.sh
Icon=camera-web
Terminal=true
Type=Application
Categories=Network;System;
EOF

echo "QR code scanning tools installed successfully."
