#!/bin/bash

for i in "$@"; do
  case $i in
    --environment-group-uuid=*)
      ENVIRONMENT_GROUP_UUID="${i#*=}"
      shift
      ;;
    --*)
      echo "Unknown option $i" >&2
      exit 1
      ;;
    *)
      ;;
  esac
done

MISSING=""
[ -z "$ENVIRONMENT_GROUP_UUID" ] && MISSING="${MISSING} environment-group-uuid"
[ ! -z "$MISSING" ] && echo "Missing arguments:$MISSING" >&2 && exit 1

INSTANCE_NAME=layerops-${ENVIRONMENT_GROUP_UUID:0:8}

INSTANCE_INFO=$(incus list $INSTANCE_NAME -f compact,noheader 2>&1 | grep $INSTANCE_NAME)
if echo "$INSTANCE_INFO" | grep -q 'Error'; then
  if echo "$INSTANCE_INFO" | grep -qi 'not found'; then
    echo "Instance '$INSTANCE_NAME' does not exist."
    exit 0
  fi
  echo "Error checking instance status: $INSTANCE_INFO" >&2
  exit 1
fi

INSTANCE_STATUS=$(echo "$INSTANCE_INFO" | awk '{print $2}')
if [ -z "$INSTANCE_STATUS" ]; then
  echo "Instance '$INSTANCE_NAME' does not exist."
  exit 0
fi

if [ "$INSTANCE_STATUS" = "RUNNING" ]; then
  err=$(incus stop $INSTANCE_NAME --timeout 60 2>&1)
  if [ $? -ne 0 ]; then
    err=$(incus stop $INSTANCE_NAME --force 2>&1)
    [ $? -ne 0 ] && echo $err >&2 && exit 1
  fi
fi

err=$(incus delete $INSTANCE_NAME 2>&1)
delete_exit_code=$?

if [ $delete_exit_code -ne 0 ]; then
  # If the error indicates that the operation succeeded despite the error, check if the instance still exists
  if echo "$err" | grep -qi "has now succeeded"; then
    # Check if the instance still exists
    INSTANCE_CHECK=$(incus list $INSTANCE_NAME -f compact,noheader 2>&1 | grep $INSTANCE_NAME)
    if [ -z "$INSTANCE_CHECK" ]; then
      # The instance no longer exists, the operation succeeded
      echo "Instance '$INSTANCE_NAME' deleted successfully (operation succeeded)."
    else
      # The instance still exists, this is a real error
      echo "$err" >&2
      exit 1
    fi
  elif echo "$err" | grep -qi 'not found'; then
    echo "Instance '$INSTANCE_NAME' already deleted."
  else
    echo "$err" >&2
    exit 1
  fi
fi
