#!/bin/bash
#===============================================================================
# SCRIPT: ruya-gce-provisioner.sh
# DESCRIPTION: Provisions a new Google Cloud VM instance using the Ruya server image
# AUTHOR: muhammad.shaban.dev@gmail.com
# DATE CREATED: March 9, 2025
# LAST MODIFIED: April 15, 2025
#
# USAGE: ./ruya-gce-provisioner.sh
#
# DEPENDENCIES:
#   - gcloud CLI tool (Google Cloud SDK)
#   - SSH key for authentication
#===============================================================================

#-------------------------------------------------------------------------------
# ANSI Color Codes for better log readability
#-------------------------------------------------------------------------------
readonly RED='\033[0;31m'
readonly GREEN='\033[0;32m'
readonly YELLOW='\033[0;33m'
readonly BLUE='\033[0;34m'
readonly NC='\033[0m'

#-------------------------------------------------------------------------------
# Logging Functions
#-------------------------------------------------------------------------------
log_info() {
    echo -e "[$(date '+%Y-%m-%d %H:%M:%S')] ${BLUE}INFO:${NC} $1"
}

log_success() {
    echo -e "[$(date '+%Y-%m-%d %H:%M:%S')] ${GREEN}SUCCESS:${NC} $1"
}

log_warning() {
    echo -e "[$(date '+%Y-%m-%d %H:%M:%S')] ${YELLOW}WARNING:${NC} $1"
}

log_error() {
    echo -e "[$(date '+%Y-%m-%d %H:%M:%S')] ${RED}ERROR:${NC} $1"
}

#-------------------------------------------------------------------------------
# Function: check_gcloud
# Description: Verifies if gcloud CLI is installed and available in the PATH
# Parameters: None
# Returns: 0 if gcloud is available, exits with code 1 otherwise
#-------------------------------------------------------------------------------
check_gcloud() {
    log_info "Checking if gcloud CLI is installed..."
    
    if command -v gcloud &> /dev/null; then
        log_success "gcloud command is available"
        log_info "gcloud version information:"
        gcloud --version | sed 's/^/    /'
    else
        log_error "gcloud command is NOT available on your system"
        log_info "To install Google Cloud SDK, please visit: https://cloud.google.com/sdk/docs/install"
        exit 1
    fi
}

#-------------------------------------------------------------------------------
# Function: get_input
# Description: Prompts user for input with a default value
# Parameters:
#   $1 - Prompt message
#   $2 - Default value
# Returns: User input or default value if input is empty
#-------------------------------------------------------------------------------
get_input() {
    local prompt="$1"
    local default="$2"
    local input
    
    # If default is empty, don't show brackets
    if [ -z "$default" ]; then
        read -p "$prompt: " input
    else
        read -p "$prompt [$default]: " input
    fi
    
    echo "${input:-$default}"
}

#-------------------------------------------------------------------------------
# Function: get_password
# Description: Prompts user for password input (hidden)
# Parameters:
#   $1 - Prompt message
# Returns: Password input
#-------------------------------------------------------------------------------
get_password() {
    local prompt="$1"
    local password
    
    while true; do
        # Get password without echoing to terminal
        read -s -p "$prompt: " password
        echo >&2
        
        # Check if password is empty
        if [ -z "$password" ]; then
            log_warning "Password cannot be empty. Please try again."
            continue
        fi
        
        # Confirm password
        read -s -p "Confirm password: " password_confirm
        echo >&2
        
        # Check if passwords match
        if [ "$password" = "$password_confirm" ]; then
            printf "%s" "$password"
            return
        else
            log_warning "Passwords do not match. Please try again."
        fi
    done
}

#-------------------------------------------------------------------------------
# Function: get_yes_no
# Description: Prompts user for yes/no input with a default value
# Parameters:
#   $1 - Prompt message
#   $2 - Default value (y or n)
# Returns: "y" for yes, "n" for no
#-------------------------------------------------------------------------------
get_yes_no() {
    local prompt="$1"
    local default="$2"
    local input
    
    while true; do
        # Format the prompt based on the default
        if [ "$default" = "y" ]; then
            read -p "$prompt [Y/n]: " input
            input="${input:-y}"
        else
            read -p "$prompt [y/N]: " input
            input="${input:-n}"
        fi
        
        # Convert to lowercase
        input=$(echo "$input" | tr '[:upper:]' '[:lower:]')
        
        # Check for valid input
        if [[ "$input" =~ ^[yn]$ ]]; then
            echo "$input"
            return
        else
            log_warning "Invalid input. Please enter 'y' for yes or 'n' for no."
        fi
    done
}

#-------------------------------------------------------------------------------
# Function: validate_input
# Description: Validates that input is not empty
# Parameters:
#   $1 - Variable name (for error message)
#   $2 - Variable value to check
# Returns: Nothing if valid, exits with code 1 if invalid
#-------------------------------------------------------------------------------
validate_input() {
    local var_name="$1"
    local var_value="$2"
    
    if [ -z "$var_value" ]; then
        log_error "$var_name cannot be empty"
        exit 1
    fi
}

#-------------------------------------------------------------------------------
# Function: create_startup_script
# Description: Creates a temporary startup script based on user configuration
# Parameters:
#   $1 - GPU installation flag
#   $2 - GUI installation flag
#   $3 - VNC server installation flag
#   $4 - User password
#   $5 - Cockpit service flag
# Returns: Path to the created startup script
#-------------------------------------------------------------------------------
create_startup_script() {
    local install_gpu_driver="$1"
    local install_gui="$2"
    local install_vnc="$3"
    local user_name="ruya"
    local user_password="$4"
    local enable_cockpit="$5"

    # Create a temporary file with a unique name
    local temp_script_path
    temp_script_path="/tmp/ruya_startup_script_`date +%s`.sh"

    # Start creating the script
    cat > "$temp_script_path" << EOF
#!/bin/bash

# Log file for startup script
export LOGFILE="/var/log/ruya-startup.log"

# Set user name and password
export USER_NAME="$user_name"
export USER_PASSWORD="$user_password"

# Function to log messages
log_message() {
    echo "\$(date '+%Y-%m-%d %H:%M:%S') - \$1" | tee -a "\$LOGFILE"
}

# Create log file
touch "\$LOGFILE"
chmod 644 "\$LOGFILE"

log_message "Starting Ruya customization script"

log_message "Updating system packages..."
dnf makecache >> "\$LOGFILE" 2>&1
dnf update -y >> "\$LOGFILE" 2>&1
EOF

    if [ -n "$user_password" ]; then
        cat >> "$temp_script_path" << EOF

log_message "Setting user password..."
echo "\$USER_NAME:\$USER_PASSWORD" | chpasswd
EOF
    fi

    # Add GUI installation if requested
    if [ "$install_gui" = "y" ]; then
        cat >> "$temp_script_path" << 'EOF'

# Install GUI
log_message "Installing GUI environment..."
if [ -f /usr/bin/install-gui ]; then
    /usr/bin/install-gui >> "$LOGFILE" 2>&1
    log_message "GUI installation completed"
else
    log_message "ERROR: GUI installation script not found at /usr/bin/install-gui"
fi
EOF
    fi

    # Add VNC server installation if requested
    if [ "$install_vnc" = "y" ]; then
        cat >> "$temp_script_path" << EOF

# Install VNC server
log_message "Installing VNC server..."
if [ -f /usr/bin/install-vnc ]; then
    /usr/bin/install-vnc >> "\$LOGFILE" 2>&1
    log_message "VNC server installation completed"
else
    log_message "ERROR: VNC server installation script not found at /usr/bin/install-vnc"
fi
EOF
    fi

    # Add Cockpit service enablement if requested
    if [ "$enable_cockpit" = "y" ]; then
        cat >> "$temp_script_path" << 'EOF'

# Enable Cockpit service
log_message "Enabling Cockpit service..."
systemctl enable --now cockpit >> "$LOGFILE" 2>&1
if [ $? -eq 0 ]; then
    log_message "Cockpit service enabled successfully"
else
    log_message "ERROR: Failed to enable Cockpit service"
fi
EOF
    fi

    # Add GUI installation if requested
    if [ "$install_gpu_driver" = "y" ]; then
        cat >> "$temp_script_path" << 'EOF'

# Install GPU driver
log_message "Installing GPU driver..."
if [ -f /usr/bin/nvidia-cli ]; then
    /usr/bin/nvidia-cli install >> "$LOGFILE" 2>&1
    log_message "GPU installation completed"
else
    log_message "ERROR: GPU installation script not found at /usr/bin/nvidia-cli"
fi
EOF
    fi

    # Finalize the script
    cat >> "$temp_script_path" << 'EOF'

log_message "Ruya customization script completed"
EOF

    # Make the script executable
    chmod +x "$temp_script_path"

    echo "$temp_script_path"
}

#===============================================================================
# MAIN SCRIPT EXECUTION
#===============================================================================

log_info "Starting Ruya GCE VM provisioning script"
log_info "========================================"

# Check if gcloud CLI is available
check_gcloud

#-------------------------------------------------------------------------------
# Collect user inputs for VM configuration
#-------------------------------------------------------------------------------
log_info "Collecting VM configuration parameters"
log_info "========================================"

# Project ID (mandatory, no default)
PROJECT_ID=$(get_input "Enter Project ID" "")
validate_input "Project ID" "$PROJECT_ID"
log_info "Project ID set to: $PROJECT_ID"

# Instance Name (mandatory, no default)
INSTANCE_NAME=$(get_input "Enter Instance Name" "")
validate_input "Instance Name" "$INSTANCE_NAME"
log_info "Instance Name set to: $INSTANCE_NAME"

# Zone (with default)
ZONE=$(get_input "Enter Zone" "us-central1-a")
validate_input "Zone" "$ZONE"
log_info "Zone set to: $ZONE"

# Machine Type (with default)
MACHINE_TYPE=$(get_input "Enter Machine Type" "e2-medium")
validate_input "Machine Type" "$MACHINE_TYPE"
log_info "Machine Type set to: $MACHINE_TYPE"

# Ask user if VM supports NVIDIA GPUs
GPU_SUPPORT=$(get_yes_no "Does this VM type support NVIDIA GPUs?" "n")
if [ "$GPU_SUPPORT" = "y" ]; then
    log_info "VM configured for NVIDIA GPU support"
    USE_GPU=true
else
    log_info "VM configured without GPU support"
    USE_GPU=false
fi

# Disk Size (with default)
DISK_SIZE=$(get_input "Enter Disk Size in GB" "20")
validate_input "Disk Size" "$DISK_SIZE"
log_info "Disk Size set to: ${DISK_SIZE}GB"

# Ask user if VM needs GUI support
GUI_SUPPORT=$(get_yes_no "Do you need GUI support?" "n")
if [ "$GUI_SUPPORT" = "y" ]; then
    log_info "VM configured with GUI support"
    
    # If GUI is requested, ask about VNC server
    VNC_SUPPORT=$(get_yes_no "Do you want to activate VNC server for remote desktop access?" "n")
else
    log_info "VM configured without GUI support"
    VNC_SUPPORT="n"
fi

# Ask user if they want to activate Cockpit web console
COCKPIT_SUPPORT=$(get_yes_no "Do you want to activate Cockpit web console for system management?" "n")
if [ "$COCKPIT_SUPPORT" = "y" ]; then
    log_info "VM configured with Cockpit web console"
    COCKPIT_PORT="9090"
    log_info "Cockpit will be accessible on port $COCKPIT_PORT"
else
    log_info "VM configured without Cockpit web console"
fi

if [ "$VNC_SUPPORT" = "y" ] || [ "$COCKPIT_SUPPORT" = "y" ]; then
    log_info "VM configured with user access password"
    USER_PASSWORD=$(get_password "Enter user access password")
    log_info "User access password set"
else
    log_info "User access password not set"
    USER_PASSWORD=""
fi

#-------------------------------------------------------------------------------
# SSH Key Configuration
#-------------------------------------------------------------------------------
log_info "Configuring SSH authentication"

# Get SSH public key path
SSH_KEY_PATH=$(get_input "Enter path to SSH public key" "~/.ssh/id_rsa.pub")
validate_input "SSH Key Path" "$SSH_KEY_PATH"
# Expand the tilde to home directory if present
SSH_KEY_PATH="${SSH_KEY_PATH/#\~/$HOME}"
log_info "Using SSH key from: $SSH_KEY_PATH"

# Verify SSH key file exists
if [ ! -f "$SSH_KEY_PATH" ]; then
    log_error "SSH key file not found at $SSH_KEY_PATH"
    log_info "Please check the path and try again"
    exit 1
fi

# Read the SSH public key content
SSH_PUBLIC_KEY=$(cat "$SSH_KEY_PATH")
log_info "SSH public key loaded successfully"

#-------------------------------------------------------------------------------
# Ruya Server Image Configuration
#-------------------------------------------------------------------------------
# These values are predefined and hardcoded for the Ruya server image
IMAGE_PROJECT_ID="temp-431411"
IMAGE_FAMILY="ruya-server"
IMAGE_DEFAULT_USER="ruya"
IMAGE_NAME_REGEX="ruya-server-[0-9]"

# Fetch the latest Ruya server image from the specified project and family
IMAGE_NAME=$(gcloud compute images list --filter="family:${IMAGE_FAMILY}" --sort-by="~creationTimestamp" --format="table(name,family,creationTimestamp)" | grep "${IMAGE_NAME_REGEX}" | head -1 | awk '{print $1}')
log_info "Using Ruya server image: $IMAGE_NAME from project: $IMAGE_PROJECT_ID"

#-------------------------------------------------------------------------------
# Create startup script based on user configuration
#-------------------------------------------------------------------------------
log_info "Creating startup script for VM customization..."
STARTUP_SCRIPT_PATH=$(create_startup_script "$GPU_SUPPORT" "$GUI_SUPPORT" "$VNC_SUPPORT" "$USER_PASSWORD" "$COCKPIT_SUPPORT")

# Verify the startup script exists
if [ ! -f "$STARTUP_SCRIPT_PATH" ]; then
    log_error "Failed to create startup script"
    exit 1
fi

# Set allowed firewall rules based on user configuration
INSTANCE_TAGS="allow-ssh"
if [ "$VNC_SUPPORT" = "y" ]; then
    INSTANCE_TAGS="$INSTANCE_TAGS,allow-vnc"
fi
if [ "$COCKPIT_SUPPORT" = "y" ]; then
    INSTANCE_TAGS="$INSTANCE_TAGS,allow-cockpit"
fi

log_info "Startup script created at: $STARTUP_SCRIPT_PATH"

#-------------------------------------------------------------------------------
# Display Configuration Summary
#-------------------------------------------------------------------------------
log_info "Configuration summary:"
echo -e "\n=== VM Configuration Summary ====================================="
echo -e "  Project ID:       ${BLUE}$PROJECT_ID${NC}"
echo -e "  Instance Name:    ${BLUE}$INSTANCE_NAME${NC}"
echo -e "  Zone:             ${BLUE}$ZONE${NC}"
echo -e "  Machine Type:     ${BLUE}$MACHINE_TYPE${NC}"
echo -e "  GUI Support:      ${BLUE}$([ "$GUI_SUPPORT" = "y" ] && echo "Yes" || echo "No")${NC}"
echo -e "  VNC Support:      ${BLUE}$([ "$VNC_SUPPORT" = "y" ] && echo "Yes" || echo "No")${NC}"
echo -e "  Cockpit Console:  ${BLUE}$([ "$COCKPIT_SUPPORT" = "y" ] && echo "Yes" || echo "No")${NC}"
echo -e "  GPU Support:      ${BLUE}$([ "$USE_GPU" = true ] && echo "Yes" || echo "No")${NC}"
echo -e "  Disk Size:        ${BLUE}${DISK_SIZE}GB${NC}"
echo -e "  Image Name:       ${BLUE}$IMAGE_NAME${NC}"
echo -e "  Image Project:    ${BLUE}$IMAGE_PROJECT_ID${NC}"
echo -e "  Default User:     ${BLUE}$IMAGE_DEFAULT_USER${NC}"
echo -e "  SSH Key Path:     ${BLUE}$SSH_KEY_PATH${NC}"
echo -e "  Startup Script:   ${BLUE}$STARTUP_SCRIPT_PATH${NC}"
echo -e "  Instance Tags:    ${BLUE}$INSTANCE_TAGS${NC}"
echo -e "=================================================================="

#-------------------------------------------------------------------------------
# Confirm Before Proceeding
#-------------------------------------------------------------------------------
read -p "Do you want to proceed with this configuration? (y/n): " confirm
if [[ ! "$confirm" =~ ^[Yy]$ ]]; then
    log_warning "Operation cancelled by user"
    exit 0
fi

#-------------------------------------------------------------------------------
# GCP Authentication
#-------------------------------------------------------------------------------
log_info "Checking Google Cloud authentication status..."

# Check if already authenticated and with the correct project
CURRENT_AUTH=$(gcloud auth list --filter=status:ACTIVE --format="value(account)" 2>/dev/null)
CURRENT_PROJECT=$(gcloud config get-value project 2>/dev/null)

if [ -n "$CURRENT_AUTH" ]; then
    log_info "Currently authenticated as: $CURRENT_AUTH"
    
    if [ "$CURRENT_PROJECT" == "$PROJECT_ID" ]; then
        log_success "Already authenticated with the correct project: $PROJECT_ID"
    else
        log_info "Switching to project: $PROJECT_ID"
        gcloud config set project "$PROJECT_ID"
        
        if [ $? -ne 0 ]; then
            log_error "Failed to switch to project: $PROJECT_ID"
            log_info "Attempting to authenticate again..."
            gcloud auth login --project "$PROJECT_ID"
        else
            log_success "Successfully switched to project: $PROJECT_ID"
        fi
    fi
else
    log_info "No active authentication found. Authenticating with Google Cloud..."
    gcloud auth login --project "$PROJECT_ID"
    
    # Check authentication status
    if [ $? -ne 0 ]; then
        log_error "Authentication failed. Please check your credentials and try again"
        exit 1
    fi
    log_success "Authentication successful"
fi

# Verify current active configuration
ACTIVE_ACCOUNT=$(gcloud auth list --filter=status:ACTIVE --format="value(account)")
ACTIVE_PROJECT=$(gcloud config get-value project)
log_info "Proceeding with account: $ACTIVE_ACCOUNT and project: $ACTIVE_PROJECT"

#-------------------------------------------------------------------------------
# Create Firewall Rules for Services if Needed
#-------------------------------------------------------------------------------

# Create SSH firewall rule if it doesn't exist
log_info "Checking SSH firewall rule..."
if ! gcloud compute firewall-rules describe allow-ssh &>/dev/null; then
    log_info "Creating firewall rule for SSH on port 22..."
    gcloud compute firewall-rules create allow-ssh \
        --direction=INGRESS \
        --priority=1000 \
        --network=default \
        --action=ALLOW \
        --rules=tcp:22 \
        --source-ranges=0.0.0.0/0 \
        --target-tags=allow-ssh \
        --description="Allow SSH connections"
        
    if [ $? -eq 0 ]; then
        log_success "Firewall rule for SSH created successfully"
    else
        log_error "Failed to create firewall rule for SSH"
    fi
else
    log_info "Firewall rule 'allow-ssh' already exists. Skipping creation."
fi

# Create firewall rule for VNC if requested
if [ "$VNC_SUPPORT" = "y" ]; then
    log_info "Checking VNC firewall rule..."
    
    # Check if firewall rule already exists
    if ! gcloud compute firewall-rules describe allow-vnc &>/dev/null; then
        log_info "Creating firewall rule for VNC server on port $VNC_PORT..."
        gcloud compute firewall-rules create allow-vnc \
            --direction=INGRESS \
            --priority=1000 \
            --network=default \
            --action=ALLOW \
            --rules=tcp:$VNC_PORT \
            --source-ranges=0.0.0.0/0 \
            --target-tags=allow-vnc \
            --description="Allow VNC server connections"
            
        if [ $? -eq 0 ]; then
            log_success "Firewall rule for VNC created successfully"
        else
            log_error "Failed to create firewall rule for VNC"
        fi
    else
        log_info "Firewall rule 'allow-vnc' already exists. Skipping creation."
    fi
fi

# Create firewall rule for Cockpit if requested
if [ "$COCKPIT_SUPPORT" = "y" ]; then
    log_info "Checking Cockpit firewall rule..."
    
    # Check if firewall rule already exists
    if ! gcloud compute firewall-rules describe allow-cockpit &>/dev/null; then
        log_info "Creating firewall rule for Cockpit web console on port $COCKPIT_PORT..."
        gcloud compute firewall-rules create allow-cockpit \
            --direction=INGRESS \
            --priority=1000 \
            --network=default \
            --action=ALLOW \
            --rules=tcp:$COCKPIT_PORT \
            --source-ranges=0.0.0.0/0 \
            --target-tags=allow-cockpit \
            --description="Allow Cockpit web console connections"
            
        if [ $? -eq 0 ]; then
            log_success "Firewall rule for Cockpit created successfully"
        else
            log_error "Failed to create firewall rule for Cockpit"
        fi
    else
        log_info "Firewall rule 'allow-cockpit' already exists. Skipping creation."
    fi
fi

#-------------------------------------------------------------------------------
# VM Instance Creation with Variable Approach
#-------------------------------------------------------------------------------
log_info "Creating VM instance '$INSTANCE_NAME'..."
log_info "This may take a few minutes..."

# Initialize additional parameters variable
ADDITIONAL_PARAMS=""

# Set additional parameters based on GPU support
if [ "$USE_GPU" = true ]; then
    log_info "Using GPU-accelerated instance with TERMINATE maintenance policy"
    ADDITIONAL_PARAMS="--maintenance-policy=TERMINATE"
else
    log_info "Using standard instance without TERMINATE maintenance policy"
    # Keep ADDITIONAL_PARAMS empty
fi

# Create VM instance with the appropriate parameters
gcloud compute instances create "$INSTANCE_NAME" \
  --image="$IMAGE_NAME" \
  --image-project="$IMAGE_PROJECT_ID" \
  --zone="$ZONE" \
  --machine-type="$MACHINE_TYPE" \
  --metadata=enable-oslogin=TRUE,enable-osconfig=TRUE,serial-port-enable=TRUE,ssh-keys="${IMAGE_DEFAULT_USER}:${SSH_PUBLIC_KEY}" \
  --metadata-from-file=startup-script="${STARTUP_SCRIPT_PATH}" \
  --boot-disk-size="${DISK_SIZE}GB" \
  --boot-disk-type=pd-balanced \
  --network=default \
  --restart-on-failure \
  --tags="$INSTANCE_TAGS" \
  $ADDITIONAL_PARAMS

# Check if instance creation was successful
if [ $? -eq 0 ]; then
    log_success "Instance '$INSTANCE_NAME' created successfully!"
    
    # Get the external IP address of the instance
    log_info "Fetching external IP address..."
    PUBLIC_IP=$(gcloud compute instances describe "$INSTANCE_NAME" --zone="$ZONE" --format="value(networkInterfaces[0].accessConfigs[0].natIP)")

    # Display connection instructions
    echo
    log_info "Connection Information:"
    echo -e "  You can connect to the instance using the following command:"
    echo -e "  ${GREEN}ssh -i $SSH_KEY_PATH ${IMAGE_DEFAULT_USER}@${PUBLIC_IP}${NC}"
    echo -e "  or using gcloud CLI:"
    echo -e "  ${GREEN}gcloud compute ssh ${IMAGE_DEFAULT_USER}@${INSTANCE_NAME} --zone=${ZONE}${NC}"
    
    # Display additional information based on configuration
    if [ "$COCKPIT_SUPPORT" = "y" ]; then
        echo
        log_info "Cockpit Web Console Information:"
        echo -e "  Once the VM is fully provisioned, you can access the Cockpit web console at:"
        echo -e "  ${GREEN}https://${PUBLIC_IP}:9090${NC}"
    fi
    
    if [ "$VNC_SUPPORT" = "y" ]; then
        echo
        log_info "VNC Server Information:"
        echo -e "  Once the VM is fully provisioned, you can connect to VNC using any VNC client at:"
        echo -e "  ${GREEN}${PUBLIC_IP}:5901${NC}"
        echo -e "  Use the VNC password you provided during setup to authenticate"
        echo -e "  NOTE: You may need to setup an SSH tunnel for secure VNC access"
    fi
    
    echo
    log_info "VM details can be viewed in the Google Cloud Console:"
    echo -e "  ${BLUE}https://console.cloud.google.com/compute/instancesDetail/zones/${ZONE}/instances/${INSTANCE_NAME}${NC}"
    
    # Display information about the startup script
    echo
    log_info "Startup Script Information:"
    echo -e "  A startup script has been configured to set up the requested services"
    echo -e "  You can monitor the progress by checking the serial console output or by running:"
    echo -e "  ${GREEN}gcloud compute ssh ${IMAGE_DEFAULT_USER}@${INSTANCE_NAME} --zone=${ZONE} --command='sudo tail -f /var/log/ruya-startup.log'${NC}"
else
    log_error "Failed to create instance. Please check the error message above"
    log_info "Troubleshooting tips:"
    log_info "  1. Verify your Google Cloud project has enough quota available"
    log_info "  2. Check if the specified zone supports the requested machine type"
    log_info "  3. Ensure the image exists in the specified project"
    log_info "  4. If you selected GPU support, verify that your machine type actually supports GPUs"
    exit 1
fi

echo

# Clean up temporary startup script file
if [ -f "$STARTUP_SCRIPT_PATH" ]; then
    log_info "Cleaning up temporary startup script..."
    rm -f "$STARTUP_SCRIPT_PATH"
fi

log_info "Waiting for 1 minute to allow the instance to initialize..."
sleep 1m

log_info "Provisioning complete. You can now connect to your instance."

echo
log_warning "======================================================================================"
log_warning "SETUP TIME REMINDER: Allow approximately 25 minutes for all services to be fully configured."
log_warning "If you encounter any issues, please check the logs at /var/log/ruya-startup.log"
log_warning "======================================================================================"
