#!/usr/bin/bash
export OCI_IDENTITY_DOMAIN="Default"

# Configuration variables
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.aaaaaaaawpuh2omgoyqorcgzyrozpjgi55rker4nblvxrtanzwtc6jchgoba"   # E.g., Ubuntu 22.04 or 24.04 San Jose Image ID

SSH_KEY_FILE="$HOME/.ssh/id_rsa.pub"
INSTANCE_NAME="ampere-free-vps"

SHAPE="VM.Standard.A1.Flex"
OCPUS=2
MEMORY_IN_GBS=12

AVAILABILITY_DOMAIN=$(oci iam availability-domain list -c "$COMPARTMENT_ID" --query "data[0].name" --raw-output)

echo "$AVAILABILITY_DOMAIN"

attempt=1 

while true; do
  echo "[$(date +'%Y-%m-%d %H:%M:%S')] Attempt #$attempt: Trying to launch instance..."
  
  # OCI launch instance command
    oci compute instance launch \
    --availability-domain "$AVAILABILITY_DOMAIN" \
    --compartment-id "$COMPARTMENT_ID" \
    --shape "$SHAPE" \
    --shape-config "{\"ocpus\":$OCPUS,\"memoryInGBs\":$MEMORY_IN_GBS}" \
    --image-id "$IMAGE_ID" \
    --subnet-id "$SUBNET_ID" \
    --assign-public-ip true \
    --display-name "$INSTANCE_NAME" \
    --ssh-authorized-keys-file ~/.ssh/id_rsa.pub \
    --wait-for-state RUNNING
    
  # 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