#!/bin/bash
# ============================================================================
# Coolify Setup Script for Google Cloud Platform - Montreal Region
# ============================================================================
# CRITICAL: ALL resources will be created in northamerica-northeast1 (Montreal)
# 
# This script will:
# 1. Create a VM in Montreal with proper specifications
# 2. Configure firewall rules
# 3. Reserve a static IP
# 4. Install Coolify
# 5. Configure security
#
# Prerequisites:
# - gcloud CLI installed (https://cloud.google.com/sdk/docs/install)
# - Authenticated with GCP: gcloud auth login
# - Project set: gcloud config set project master-ai-484822
# ============================================================================

set -e  # Exit on any error

# ============================================================================
# CONFIGURATION - MONTREAL REGION ONLY
# ============================================================================
PROJECT_ID="master-ai-484822"
REGION="northamerica-northeast1"  # MONTREAL - DO NOT CHANGE
ZONE="northamerica-northeast1-a"  # MONTREAL ZONE A
VM_NAME="coolify-server-mtl"
MACHINE_TYPE="n2-standard-2"  # 2 vCPU, 8GB RAM (~$70/month)
BOOT_DISK_SIZE="100GB"
STATIC_IP_NAME="coolify-static-ip-mtl"

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

# ============================================================================
# FUNCTIONS
# ============================================================================

print_header() {
    echo -e "\n${BLUE}============================================${NC}"
    echo -e "${BLUE}$1${NC}"
    echo -e "${BLUE}============================================${NC}\n"
}

print_success() {
    echo -e "${GREEN}✅ $1${NC}"
}

print_error() {
    echo -e "${RED}❌ $1${NC}"
}

print_warning() {
    echo -e "${YELLOW}⚠️  $1${NC}"
}

print_info() {
    echo -e "${BLUE}ℹ️  $1${NC}"
}

# ============================================================================
# MAIN SETUP
# ============================================================================

print_header "Coolify Setup - Montreal Region (northamerica-northeast1)"

echo "This script will create:"
echo "  - VM in Montreal (northamerica-northeast1-a)"
echo "  - Static IP address"
echo "  - Firewall rules"
echo "  - Install Coolify"
echo ""
echo "Estimated cost: ~\$70/month"
echo "Estimated time: ~15-20 minutes"
echo ""

read -p "Continue? (y/n) " -n 1 -r
echo
if [[ ! $REPLY =~ ^[Yy]$ ]]; then
    print_error "Setup cancelled"
    exit 1
fi

# ============================================================================
# STEP 1: Set Project and Verify Montreal Region
# ============================================================================

print_header "Step 1: Configure GCP Project"

print_info "Setting project to: $PROJECT_ID"
gcloud config set project $PROJECT_ID

print_info "Verifying Montreal region availability..."
if gcloud compute regions describe $REGION &>/dev/null; then
    print_success "Montreal region ($REGION) is available!"
else
    print_error "Montreal region not available in your project!"
    exit 1
fi

# ============================================================================
# STEP 2: Enable Required APIs
# ============================================================================

print_header "Step 2: Enable Required APIs"

print_info "Enabling Compute Engine API..."
gcloud services enable compute.googleapis.com

print_success "APIs enabled"

# ============================================================================
# STEP 3: Reserve Static IP (in Montreal)
# ============================================================================

print_header "Step 3: Reserve Static IP in Montreal"

# Check if IP already exists
if gcloud compute addresses describe $STATIC_IP_NAME --region=$REGION &>/dev/null; then
    print_warning "Static IP already exists"
    STATIC_IP=$(gcloud compute addresses describe $STATIC_IP_NAME --region=$REGION --format="get(address)")
else
    print_info "Creating static IP in Montreal region..."
    gcloud compute addresses create $STATIC_IP_NAME \
        --region=$REGION
    
    STATIC_IP=$(gcloud compute addresses describe $STATIC_IP_NAME --region=$REGION --format="get(address)")
    print_success "Static IP created: $STATIC_IP"
fi

echo ""
print_info "Your Coolify will be accessible at: $STATIC_IP"
echo ""

# ============================================================================
# STEP 4: Create Firewall Rules
# ============================================================================

print_header "Step 4: Configure Firewall Rules"

# Coolify ports firewall rule
if gcloud compute firewall-rules describe allow-coolify-ports &>/dev/null; then
    print_warning "Coolify firewall rule already exists"
else
    print_info "Creating firewall rule for Coolify ports..."
    gcloud compute firewall-rules create allow-coolify-ports \
        --direction=INGRESS \
        --priority=1000 \
        --network=default \
        --action=ALLOW \
        --rules=tcp:8000,tcp:6001,tcp:6002 \
        --source-ranges=0.0.0.0/0 \
        --description="Allow Coolify dashboard and services"
    
    print_success "Firewall rules created"
fi

# ============================================================================
# STEP 5: Create VM Instance in Montreal
# ============================================================================

print_header "Step 5: Create VM Instance in Montreal"

# Check if VM already exists
if gcloud compute instances describe $VM_NAME --zone=$ZONE &>/dev/null; then
    print_warning "VM already exists: $VM_NAME"
    print_info "Checking if it's running..."
    
    VM_STATUS=$(gcloud compute instances describe $VM_NAME --zone=$ZONE --format="get(status)")
    if [ "$VM_STATUS" != "RUNNING" ]; then
        print_info "Starting VM..."
        gcloud compute instances start $VM_NAME --zone=$ZONE
    fi
else
    print_info "Creating VM in Montreal (this takes ~30 seconds)..."
    
    gcloud compute instances create $VM_NAME \
        --zone=$ZONE \
        --machine-type=$MACHINE_TYPE \
        --network-interface=address=$STATIC_IP,network-tier=PREMIUM \
        --metadata=startup-script='#!/bin/bash
apt-get update
' \
        --maintenance-policy=MIGRATE \
        --provisioning-model=STANDARD \
        --tags=http-server,https-server \
        --create-disk=auto-delete=yes,boot=yes,device-name=$VM_NAME,image=projects/ubuntu-os-cloud/global/images/ubuntu-2204-jammy-v20240319,mode=rw,size=$BOOT_DISK_SIZE,type=pd-balanced \
        --no-shielded-secure-boot \
        --shielded-vtpm \
        --shielded-integrity-monitoring \
        --labels=purpose=coolify,region=montreal \
        --reservation-affinity=any
    
    print_success "VM created successfully!"
fi

print_success "VM Details:"
echo "  Name: $VM_NAME"
echo "  Zone: $ZONE (Montreal)"
echo "  IP: $STATIC_IP"
echo "  Machine: $MACHINE_TYPE (2 vCPU, 8GB RAM)"
echo ""

# ============================================================================
# STEP 6: Wait for VM to be Ready
# ============================================================================

print_header "Step 6: Waiting for VM to be Ready"

print_info "Waiting for SSH to be available (this may take 30-60 seconds)..."
for i in {1..30}; do
    if gcloud compute ssh $VM_NAME --zone=$ZONE --command="echo 'SSH Ready'" &>/dev/null; then
        print_success "VM is ready!"
        break
    fi
    echo -n "."
    sleep 2
done
echo ""

# ============================================================================
# STEP 7: Install Coolify
# ============================================================================

print_header "Step 7: Install Coolify on Montreal Server"

print_info "Connecting to VM and installing Coolify..."
print_warning "This will take 5-10 minutes. Please be patient..."

gcloud compute ssh $VM_NAME --zone=$ZONE --command='
set -e

echo "📦 Updating system packages..."
sudo apt-get update -qq
sudo apt-get upgrade -y -qq

echo "🐳 Installing Docker prerequisites..."
sudo apt-get install -y -qq curl wget git

echo "🚀 Installing Coolify..."
curl -fsSL https://cdn.coollabs.io/coolify/install.sh | bash

echo ""
echo "✅ Coolify installation complete!"
echo ""
'

print_success "Coolify installed successfully!"

# ============================================================================
# STEP 8: Verify Installation
# ============================================================================

print_header "Step 8: Verify Coolify Installation"

print_info "Checking Coolify service status..."
gcloud compute ssh $VM_NAME --zone=$ZONE --command='
if systemctl is-active --quiet coolify; then
    echo "✅ Coolify service is running"
    docker ps --format "table {{.Names}}\t{{.Status}}" | grep coolify
else
    echo "❌ Coolify service is not running"
    exit 1
fi
'

print_success "Coolify is running!"

# ============================================================================
# STEP 9: Display Access Information
# ============================================================================

print_header "🎉 Setup Complete!"

echo ""
echo -e "${GREEN}═══════════════════════════════════════════════════════════${NC}"
echo -e "${GREEN}               COOLIFY SETUP SUCCESSFUL!${NC}"
echo -e "${GREEN}═══════════════════════════════════════════════════════════${NC}"
echo ""
echo -e "${BLUE}📍 Server Location:${NC} Montreal, Canada (northamerica-northeast1)"
echo -e "${BLUE}🌐 Access URL:${NC} http://$STATIC_IP:8000"
echo ""
echo -e "${YELLOW}🔐 Default Login Credentials:${NC}"
echo "   Email: root@localhost"
echo "   Password: password"
echo ""
echo -e "${RED}⚠️  CHANGE PASSWORD IMMEDIATELY after first login!${NC}"
echo ""
echo -e "${BLUE}📝 Next Steps:${NC}"
echo "   1. Open: http://$STATIC_IP:8000"
echo "   2. Login with credentials above"
echo "   3. Change password immediately"
echo "   4. Configure your domain in Coolify settings"
echo "   5. Generate API token for Vibn integration"
echo ""
echo -e "${BLUE}💾 To save your configuration:${NC}"
echo "   VM Name: $VM_NAME"
echo "   Zone: $ZONE"
echo "   IP Address: $STATIC_IP"
echo "   Region: $REGION (Montreal)"
echo ""
echo -e "${BLUE}🔗 SSH Access:${NC}"
echo "   gcloud compute ssh $VM_NAME --zone=$ZONE --project=$PROJECT_ID"
echo ""
echo -e "${GREEN}═══════════════════════════════════════════════════════════${NC}"

# ============================================================================
# STEP 10: Save Configuration
# ============================================================================

CONFIG_FILE="coolify-montreal-config.txt"

cat > $CONFIG_FILE << EOF
# Coolify Configuration - Montreal Setup
# Created: $(date)
# ============================================

GCP Project: $PROJECT_ID
Region: $REGION (Montreal, Canada)
Zone: $ZONE
VM Name: $VM_NAME
Machine Type: $MACHINE_TYPE
Static IP: $STATIC_IP

Access URL: http://$STATIC_IP:8000
Default Email: root@localhost
Default Password: password

SSH Command:
gcloud compute ssh $VM_NAME --zone=$ZONE --project=$PROJECT_ID

VM Management:
- Start: gcloud compute instances start $VM_NAME --zone=$ZONE
- Stop: gcloud compute instances stop $VM_NAME --zone=$ZONE
- Delete: gcloud compute instances delete $VM_NAME --zone=$ZONE

Next Steps:
1. Access Coolify at http://$STATIC_IP:8000
2. Change password immediately
3. Configure domain for HTTPS
4. Create API token for Vibn
5. Deploy test application

Security Notes:
- Change default password IMMEDIATELY
- Configure SSL certificate after domain setup
- Enable 2FA if available
- Store API tokens securely
EOF

print_success "Configuration saved to: $CONFIG_FILE"
echo ""
print_info "Opening Coolify URL in browser..."

# Try to open in browser (works on Mac/Linux with default browser)
if command -v open &> /dev/null; then
    open "http://$STATIC_IP:8000"
elif command -v xdg-open &> /dev/null; then
    xdg-open "http://$STATIC_IP:8000"
else
    echo "Please manually open: http://$STATIC_IP:8000"
fi

echo ""
print_success "Setup complete! Coolify is ready in Montreal! 🇨🇦"
