#!/bin/bash
set -e

echo "========================================="
echo "   NexusGuard SD-WAN: INITIAL SETUP      "
echo "========================================="

# 1. Environment File Generation
if [ ! -f .env ]; then
    echo "[!] .env file not found."
    if [ -f .env.example ]; then
        echo "[+] Auto-generating .env from .env.example..."
        cp .env.example .env
        
        # Generate secure random hex keys
        RANDOM_JWT=$(openssl rand -hex 32)
        RANDOM_SALT=$(openssl rand -hex 32)
        
        sed -i "s/GantiDenganKunciRahasiaJWTUntukDashboard256Bit/$RANDOM_JWT/g" .env
        sed -i "s/GantiDenganKunciGaramUntukWireGuard256Bit/$RANDOM_SALT/g" .env
        
        echo "[+] Secure cryptographic keys have been auto-generated!"
    else
        echo "[-] ERROR: .env.example is missing. Cannot generate .env."
        exit 1
    fi
else
    echo "[+] .env file already exists. Skipping environment generation."
fi

# Make sure Docker Compose v2 is available
if ! docker compose version &> /dev/null; then
    echo "[-] ERROR: docker compose (v2) is not available. Please install Docker and Docker Compose plugin."
    exit 1
fi

echo ""
echo "========================================="
echo " Setup complete! Next Steps:             "
echo " 1. Open and review the '.env' file.     "
echo "    Make sure to change DB_PASSWORD,     "
echo "    API_PORT, and VITE_API_BASE_URL.     "
echo "                                         "
echo " 2. Run 'bash update.sh' to download the "
echo "    latest code, build, and start the    "
echo "    system. The script will also run     "
echo "    database migrations automatically.   "
echo "                                         "
echo " 3. Create your Admin account:           "
echo "    docker exec -it nexus-guard-suite-server-core-1 ./server-core -create-admin -user \"admin\" -pass \"PasswordKuat123!\""
echo "========================================="
