#!/bin/bash
# WireGuard QR Code Generator
# Generates QR codes for WireGuard client configurations
#
# Usage: ./generate-wg-qr.sh <client_name>
# Example: ./generate-wg-qr.sh device3
#
# Requires: qrencode package
# Install with: apt install -y qrencode

set -e

CLIENT_NAME=${1:-"client"}
CONFIG_DIR="/tmp/wg_qr_codes"
CONFIG_FILE="${CONFIG_DIR}/${CLIENT_NAME}.conf"
QR_FILE="${CONFIG_DIR}/${CLIENT_NAME}.qr.png"

# Create output directory
mkdir -p "$CONFIG_DIR"

# Check if qrencode is installed
if ! command -v qrencode &> /dev/null; then
    echo "Error: qrencode is not installed"
    echo "Install with: apt install -y qrencode"
    exit 1
fi

# Read config from stdin if no file exists
if [ ! -f "$CONFIG_FILE" ]; then
    echo "No existing config found. Paste WireGuard config (Ctrl+D to finish):"
    cat > "$CONFIG_FILE"
fi

# Generate QR code
echo "Generating QR code for $CLIENT_NAME..."
qrencode -o "$QR_FILE" -t PNG -r "$CONFIG_FILE"

# Display file info
echo ""
echo "✓ QR code generated: $QR_FILE"
echo "  File size: $(du -h "$QR_FILE" | cut -f1)"
echo ""
echo "Use with WireGuard app:"
echo "  1. Transfer $QR_FILE to device"
echo "  2. Open WireGuard app"
echo "  3. Tap + → Import from file → Select QR image"
echo ""
echo "Or manually copy config:"
echo "  cat $CONFIG_FILE"
