#!/bin/bash

# Quick test script for Tailscale Clone
# This script helps you quickly test the application

set -e

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

echo -e "${GREEN}Tailscale Clone - Quick Test${NC}"
echo "=================================="

# Check if Go is installed
if ! command -v go &> /dev/null; then
    echo -e "${RED}Error: Go is not installed${NC}"
    echo "Please install Go 1.21 or later"
    exit 1
fi

# Check if WireGuard is available
if ! command -v wg &> /dev/null; then
    echo -e "${YELLOW}Warning: WireGuard is not installed${NC}"
    echo "The application may not work properly without WireGuard"
    echo "Install WireGuard with: sudo apt install wireguard (Ubuntu/Debian)"
fi

# Check if running as root
if [ "$EUID" -ne 0 ]; then
    echo -e "${YELLOW}Warning: Not running as root${NC}"
    echo "Some operations may fail. Consider running with sudo"
fi

# Build the application
echo -e "${GREEN}Building application...${NC}"
go mod download
go build -o bin/controller cmd/controller/main.go
go build -o bin/client cmd/client/main.go

# Create data directory
mkdir -p data

# Function to cleanup on exit
cleanup() {
    echo -e "\n${YELLOW}Cleaning up...${NC}"
    pkill -f "bin/controller" || true
    pkill -f "bin/client" || true
    echo -e "${GREEN}Cleanup complete${NC}"
}

# Set trap to cleanup on exit
trap cleanup EXIT

# Start controller
echo -e "${GREEN}Starting controller...${NC}"
./bin/controller -port 8080 -web-port 8081 -data-dir ./data &
CONTROLLER_PID=$!

# Wait for controller to start
sleep 3

# Check if controller is running
if ! kill -0 $CONTROLLER_PID 2>/dev/null; then
    echo -e "${RED}Error: Controller failed to start${NC}"
    exit 1
fi

echo -e "${GREEN}Controller started successfully${NC}"
echo -e "${YELLOW}Web interface: http://localhost:8081${NC}"

# Start test clients
echo -e "${GREEN}Starting test clients...${NC}"

# Client 1
echo -e "${YELLOW}Starting client 1 (laptop)...${NC}"
./bin/client -name "laptop" -controller "localhost:8080" &
CLIENT1_PID=$!

sleep 2

# Client 2
echo -e "${YELLOW}Starting client 2 (desktop)...${NC}"
./bin/client -name "desktop" -controller "localhost:8080" &
CLIENT2_PID=$!

sleep 2

# Client 3
echo -e "${YELLOW}Starting client 3 (server)...${NC}"
./bin/client -name "server" -controller "localhost:8080" &
CLIENT3_PID=$!

echo -e "${GREEN}All components started successfully!${NC}"
echo ""
echo -e "${GREEN}Test Setup:${NC}"
echo "  - Controller: http://localhost:8081"
echo "  - API: http://localhost:8080"
echo "  - Clients: laptop, desktop, server"
echo ""
echo -e "${YELLOW}Press Ctrl+C to stop all components${NC}"

# Wait for user to stop
wait 