#!/usr/bin/bash
export OCI_IDENTITY_DOMAIN="Default"

# ==============================================================================
# CONFIGURATION - Replace these with your actual OCI OCIDs
# ==============================================================================
COMPARTMENT_ID="ocid1.tenancy.oc1..aaaaaaaag2ktdzyg43meie6cuotjayzopab7qp3ub7ruviwhbek5wvjaee4q"   # Found under Identity -> Compartments
SUBNET_ID="ocid1.subnet.oc1.us-sanjose-1.aaaaaaaapk3bqxxpxftargesahni7aiwyp7zr3rc5xe3buenmkzyomb2rhga" # Found under Networking -> VCN -> Subnets
IMAGE_ID="ocid1.image.oc1.us-sanjose-1.aaaaaaaalxgxfjgq3zoeq3szqajo4jfdcc2ycfqnlcaoqam7lo5jj4iztqeq"   # E.g., Ubuntu 22.04 or 24.04 San Jose Image ID

SSH_KEY_FILE="$HOME/.ssh/id_rsa.pub"
INSTANCE_NAME="Free-AMD-Micro"

# Always Free AMD shape
SHAPE="VM.Standard.E2.1.Micro"

# Automatically fetch the first Availability Domain in your region
AVAILABILITY_DOMAIN=$(oci iam availability-domain list -c "$COMPARTMENT_ID" --query "data[0].name" --raw-output)

echo "Targeting Availability Domain: $AVAILABILITY_DOMAIN"
echo "Starting launch loop for Always Free AMD micro instance..."
echo "Will retry every 5 minutes until successful."
echo "--------------------------------------------------------"

# ==============================================================================
# RETRY LOOP
# ==============================================================================
attempt=1

while true; do
    echo "[$(date +'%Y-%m-%d %H:%M:%S')] Attempt #$attempt: Trying to launch instance..."

    # Execute the OCI launch command
    # --wait-for-state RUNNING ensures the command waits until provisioning succeeds if it gets accepted
    OUTPUT=$(oci compute instance launch \
        --compartment-id "$COMPARTMENT_ID" \
        --availability-domain "$AVAILABILITY_DOMAIN" \
        --subnet-id "$SUBNET_ID" \
        --image-id "$IMAGE_ID" \
        --shape "$SHAPE" \
        --display-name "$INSTANCE_NAME" \
        --ssh-authorized-keys-file "$SSH_KEY_FILE" \
        --assign-public-ip true \
        --wait-for-state RUNNING 2>&1)

    # Check the exit status of the OCI CLI command
    if [ $? -eq 0 ]; then
        echo "--------------------------------------------------------"
        echo "SUCCESS! Compute instance successfully launched and is RUNNING."
        echo "$OUTPUT"
        break
    else
        echo "Failed to launch instance. OCI returned:"
        echo "$OUTPUT"
        echo "Pausing for 5 minutes before trying again..."
        echo "--------------------------------------------------------"
        
        # Wait 5 minutes (300 seconds)
        sleep 300
        ((attempt++))
    fi
done
