#!/bin/bash

set -euo pipefail

_handle_host() {

  _compartment=rock
  _job_id=$(cat /proc/sys/kernel/random/uuid)
  _user='root'
  
  if [[ ! -z "${SUDO_USER}" ]]; then
    _user="${SUDO_USER}"
  fi

  if [[ -f "~/.oci/config_rescue" ]]; then
    export OCI_CLI_CONFIG_FILE="~/.oci/config_rescue"
  else
    export OCI_CLI_CONFIG_FILE='/etc/oci/config_rescue'
  fi

  _mode=''
  _vm_name=''
  _tenant=''
  _supported_tenants=('bhhosting' 'bhpreprodhosting' 'dsnhosting' 'dsnpreprdhosting' 'nfpreprodhosting')
  _region=''
  _supported_regions=('us-ashburn-1' 'us-phoenix-1' 'ap-sydney-1')

  # Use getopts to parse options.
  while getopts "m:h:r:t:d" opt; do
    case "$opt" in
      m)
        _mode="$OPTARG"
        ;;
      h)
        _vm_name="$OPTARG"
	_rescue_vm_name="rescue-${_vm_name}"
        ;;
      r)
        _region="$OPTARG"
        local _match=''
        for _r in "${_supported_regions[@]}"; do
          if [[ "${_region}" == "${_r}" ]]; then
            _match=1
            break
          fi
        done
        if [[ "${_match}" -ne 1 ]]; then
          echo "Invalid region ${_region}. Supported regions: '${_supported_regions[@]}'"
          exit 1
        fi
	export OCI_CLI_REGION="${_region}"
        ;;
      t)
        _tenant="$OPTARG"
        local _match=''
        for _t in "${_supported_tenants[@]}"; do
          if [[ "${_tenant}" == "${_t}" ]]; then
            _match=1
            break
          fi
        done
        if [[ "${_match}" -ne 1 ]]; then
          echo "Invalid tenant ${_tenant}. Supported tenants: '${_supported_tenants[@]}'"
          exit 1
        fi
	export OCI_CLI_PROFILE="${_tenant}"
        ;;	
      d)
	set -x
	;;
      \?)
        echo "Invalid option: -$OPTARG" >&2
        exit 1
        ;;
      :)
        echo "Option -$OPTARG requires an argument." >&2
        exit 1
        ;;
    esac
  done

  # Validate the mode.
  if [[ "${_mode}" != "rescue" ]] && [[ "${_mode}" != "unrescue" ]]; then
    _help
  fi

  # Check if hostname is provided.
  if [[ -z "${_vm_name}" ]]; then
    _help	  
  fi
  
  # Required arguments
  if [[ -z "${_tenant}" ]] || [[ -z "${_region}" ]]; then
    _help
  fi

  # Perform the action based on the selected mode.
  if [[ "${_mode}" == "rescue" ]]; then
    echo "Performing rescue operation on ${_vm_name}..."
    _vm_rescue
  elif [[ "${_mode}" == "unrescue" ]]; then
    echo "Performing unrescue operation on ${_vm_name}..."
    _vm_unrescue
  fi

  echo "Operation completed."
}

_log_message() {
    local _message="$@"
    local _timestamp=$(date +"%Y-%m-%d %H:%M:%S")
    local _log_file='oci_rescue_instance.log'
    echo "[${_timestamp}] job_id: ${_job_id} user: ${_user} task: ${_message}" >> "/var/log/${_log_file}"
}

function _help() {
  echo "Usage: $0 -t <tenant> -r <region> -m <rescue|unrescue> -h <hostname>" >&2
  echo "  -t: OCI tenant. '${_supported_tenants[@]}'"
  echo "  -r: OCI region. '${_supported_regions[@]}'"
  echo "  -m: Mode (rescue or unrescue)."
  echo "  -h: Hostname to operate on."
  exit 1	
}

function _vm_unrescue() {
  _compartment_info
  if [[ "${_compartment_id}" =~ ocid1.compartment ]]; then
    _vm_info
    if [[ "${_instance_id}" =~ ocid1.instance ]]; then
      _rescue_tag_check
      if [[ "${_rescue_tag_value}" == '1' ]]; then
        if [[ "${_lc_state}" != 'STOPPED' ]]; then
          echo "${_vm_name} current status: ${_lc_state}, expected status: STOPPED"
          exit 1
        fi
        _rescue_vm_info
        if [[ "${_resc_lc_state}" != 'TERMINATED' ]]; then
          _boot_volume_info
          if [[ "${_boot_volume_id}" =~  ocid1.bootvolume ]]; then
            echo "Destroying rescue VM: ${_rescue_vm_name}"
            _rescue_vm_destroy
            echo "Reattaching boot volume to VM: ${_vm_name}"
            _boot_volume_attach
            if [[ "${_boot_vol_lc_state}" == 'ATTACHED' ]]; then
              _rescue_tag_delete
             echo "Starting VM: ${_vm_name}"
	      _instance_start
	      echo "${_vm_name} ${_lc_state}"
            else
  	      echo "Failed attaching boot volume to ${_vm_name}"
	    fi
          else
            echo "Failed _boot_volume_info: invalid ocid1.bootvolume ${_boot_volume_id}"
            exit 1
	  fi
	else
  	  echo "Didn't find any rescue VMs in non TERMINATED state"
	fi
      else
        echo "${_vm_name} not in rescue mode"
        exit 1
      fi
    else
      echo "failed to get instance ocid for ${_vm_name}"
      exit 1	    
    fi
  else
    echo "failed getting compartment ID for ${_compartment} compartment"
    exit 1	  
  fi
}

function _vm_rescue() {
  _compartment_info	
  if [[ "${_compartment_id}" =~ ocid1.compartment ]]; then
    _vm_info
    if [[ "${_instance_id}" =~ ocid1.instance ]]; then
      _rescue_tag_check
      if [[ "${_rescue_tag_value}" == '1' ]]; then
        echo "${_vm_name} already in rescue mode"
	_rescue_vm_info
	_rescue_vm_ip
	echo "Rescue VM info: hostname: ${_rescue_vm_name} ip: ${_resc_inst_ip}"
	exit 1
      elif [[ "${_lc_state}" != 'STOPPED' ]]; then
        echo "${_vm_name} current status: ${_lc_state}, expected status: STOPPED"
        exit 1
      fi
      _boot_volume_info
      if [[ "${_boot_volume_id}" =~  ocid1.bootvolume ]]; then
        if [[ "${_boot_vol_lc_state}" == 'DETACHED' ]]; then
          echo "${_vm_name} ${_boot_volume_id} current status: ${_boot_vol_lc_state}, expected status: ATTACHED"
  	exit 1
        elif [[ "${_boot_vol_lc_state}" == 'ATTACHED' ]]; then
          echo "Creating rescue VM: ${_rescue_vm_name}"
          _rescue_vm_create
          _rescue_vm_ip
          if [[ "${_resc_inst_id}" =~ ocid1.instance ]]; then
            echo "Detaching boot volume from VM: ${_vm_name}"
            _boot_volume_detach
            if [[ "${_boot_vol_lc_state}" == 'DETACHED' ]]; then
 	      _rescue_tag_add
              echo "Attaching boot volume to rescue VM: ${_vm_name}"
  	      _rescue_volume_attach
              if [[ "${_volume_attach_status}" != 'ATTACHED' ]]; then
                echo "Failed attaching boot disk to recue image ${_rescue_vm_name}"
	        exit 1
	      fi 
	      echo "Rescue VM info: hostname: ${_rescue_vm_name} ip: ${_resc_inst_ip}"    
            else
              echo "Failed detaching boot volume ${_boot_volume_id} from instance ${_instance_id}"
	    fi
  	  else
            echo "Failed creating ${_rescue_vm_name}"
    	    exit 1
  	  fi
        fi
      else
        echo "Failed _boot_volume_info: invalid ocid1.bootvolume ${_boot_volume_id}"
	exit 1
      fi
    else
      echo "failed to get instance ocid for ${_vm_name}"
      exit 1
    fi
  else
    echo "failed getting compartment ID for ${_compartment} compartment"
    exit 1
  fi
}

function _compartment_info() {
  _compartment_id=$(oci iam compartment list --compartment-id-in-subtree true --name "${_compartment}" --query 'data[0].id' --raw-output)
  if [[ "${_compartment_id}" =~ ocid1.compartment ]]; then
    _subnet_query='query subnet resources return identifier where definedTags.value = "rock"  && definedTags.value = "shared-hosting" && definedTags.value = "shared"'
    _img_query="query image resources where operatingSystem = 'AlmaLinux' && operatingSystemVersion = '9' && compartmentId = '${_compartment_id}' sorted by timeCreated desc"
#   _img_id=$(oci compute image list --compartment-id "${_compartment_id}" --display-name 'AlmaLinux 9 - Base' --sort-by TIMECREATED --sort-order DESC --query 'data[0].id' --raw-output)
    _img_id=$(oci search resource structured-search --query-text "${_img_query}" --query 'data.items[0].identifier' --raw-output)
    _subnet_id=$(oci search resource structured-search --query-text "${_subnet_query}" --query 'data.items[0].identifier' --raw-output)
  fi
}

function _rescue_vm_create() {
  _log_message "Create rescue VM availability_domain: ${_availabilty_dom} compartment_id: ${_compartment_id}"
  _cloud_config="$(dirname $(realpath "$0"))/cloud-config.yaml"
  if [[ ! -f "${_cloud_config}" ]]; then
    _cloud_config='/etc/oci/cloud-config.yaml'
  fi

  _resc_inst_id=$(oci compute instance launch \
    --availability-domain "${_availabilty_dom}" \
    --compartment-id "${_compartment_id}" \
    --shape VM.Standard.E5.Flex \
    --shape-config '{"memoryInGBs": 4, "ocpus": 2}' \
    --image-id "${_img_id}" \
    --subnet-id "${_subnet_id}" \
    --assign-public-ip true \
    --user-data-file "${_cloud_config}" \
    --display-name "${_rescue_vm_name}" --query 'data.id' --wait-for-state RUNNING --wait-interval-seconds 5 --max-wait-seconds 300 --raw-output)
}

function _rescue_vm_ip() {
  _log_message "Resuce VM ip info instance_id: ${_resc_inst_id}"
  _resc_inst_ip=$(oci compute instance list-vnics --instance-id ${_resc_inst_id} --query 'data[0]."public-ip"' --raw-output)
}

function _rescue_vm_destroy() {
  _log_message "stop rescue VM instance_id: ${_resc_inst_id}"
  oci compute instance action --instance-id "${_resc_inst_id}" --action SOFTSTOP --wait-for-state STOPPED --wait-interval-seconds 5 --max-wait-seconds 300 --query 'data."lifecycle-state"' --raw-output
  _log_message "destroy rescue VM instance_id: ${_resc_inst_id}"
  oci compute instance terminate --instance-id "${_resc_inst_id}" --wait-for-state TERMINATED --wait-interval-seconds 5 --max-wait-seconds 300 --force
}

function _vm_info() {
  _log_message "Find VM info display_name: ${_vm_name} compartment_id: ${_compartment_id}"
  read -r _instance_id _availabilty_dom _lc_state < <(oci compute instance list --compartment-id "${_compartment_id}" --display-name "${_vm_name}" --all --sort-by TIMECREATED --sort-order DESC --query "join(' ', [data[0].id, data[0].\"availability-domain\", data[0].\"lifecycle-state\"])" --raw-output)
}

function _rescue_vm_info() {
  _log_message "Find Rescue VM info display_name: ${_rescue_vm_name} compartment_id: ${_compartment_id}"
  read -r _resc_inst_id _resc_lc_state < <(oci compute instance list --compartment-id "${_compartment_id}" --display-name "${_rescue_vm_name}" --all --sort-by TIMECREATED --sort-order DESC --query "join(' ', [data[0].id, data[0].\"lifecycle-state\"])" --raw-output)
}

function _rescue_volume_attach() {
  _log_message "Attach boot volume to Rescue VM info volume_id: ${_boot_volume_id} instance_id: ${_resc_inst_id}"
  _volume_attach_status=$(oci compute volume-attachment attach --instance-id "${_resc_inst_id}" --volume-id "${_boot_volume_id}" --type 'paravirtualized' --wait-for-state ATTACHED --wait-interval-seconds 5 --max-wait-seconds 300 --query 'data."lifecycle-state"' --raw-output)
}

function _boot_volume_info() {
  _log_message "Find boot volume id instance_id: ${_instance_id}"
  read -r _boot_volume_id _boot_vol_lc_state < <(oci compute boot-volume-attachment get --boot-volume-attachment-id "${_instance_id}" --query "join(' ', [data.\"boot-volume-id\", data.\"lifecycle-state\"])" --raw-output)
}

function _boot_volume_detach() {
  _log_message "Detach boot volume from VM instance_id: ${_instance_id}"
  oci compute boot-volume-attachment detach --boot-volume-attachment-id "${_instance_id}" --wait-for-state DETACHED --wait-interval-seconds 5 --max-wait-seconds 300 --force &> /dev/null
  _boot_volume_info
  
}

function _boot_volume_attach() {
  _log_message "Attach boot volume to VM instance_id: ${_instance_id} boot_volume_id: ${_boot_volume_id}"
  _boot_vol_lc_state=$(oci compute boot-volume-attachment attach --boot-volume-id "${_boot_volume_id}" --instance-id "${_instance_id}" --wait-for-state ATTACHED --wait-interval-seconds 5 --max-wait-seconds 300 --query 'data."lifecycle-state"' --raw-output)
  _boot_volume_info
}

function _rescue_tag_add() {
  _log_message "Add rescue tag instance_id: ${_instance_id}"
  _rescue_tag_value=$(oci compute instance update --instance-id "${_instance_id}" --freeform-tags '{"rescue_mode": "1"}' --force --query 'data."freeform-tags".rescue_mode' --raw-output)
}

function _rescue_tag_delete() {
  _log_message "Delete rescue tag from VM instance_id: ${_instance_id}"
  _rescue_tag_value=$(oci compute instance update --instance-id "${_instance_id}" --freeform-tags '{}' --force --query 'data."freeform-tags".rescue_mode' --raw-output 2> /dev/null)
}

function _rescue_tag_check() {
  _log_message "Check rescue tag from VM instance_id: ${_instance_id}"
  _rescue_tag_value=$(oci compute instance get --instance-id "${_instance_id}" --query 'data."freeform-tags".rescue_mode' --raw-output 2> /dev/null)
}

function _instance_start() {
  _log_message "Start VM instance_id: ${_instance_id}"
  _lc_state=$(oci compute instance action --instance-id "${_instance_id}" --action START --wait-for-state RUNNING --wait-interval-seconds 5 --max-wait-seconds 300 --query 'data."lifecycle-state"' --raw-output)
}

_handle_host "$@"
