#!/usr/bin/bash

set -euo pipefail

_handle_host() {

  _compartment=rock
  _job_id=$(cat /proc/sys/kernel/random/uuid)
  _user="${SUDO_USER:-$USER}"

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

  _mode=''
  _vm_name=''
  _reboot_type=''
  _announcement_id=''
  _tenant=''
  _supported_tenants=('bhhosting' 'bhpreprodhosting' 'dsnhosting' 'dsnpreprdhosting' 'nfpreprodhosting' 'lahosting' 'lapreprodhosting' 'nfinfra')
  _region=''
  _supported_regions=('eu-amsterdam-1' 'eu-stockholm-1' 'me-abudhabi-1' 'sa-bogota-1' 'ap-mumbai-1' 'eu-paris-1' 'uk-cardiff-1' 'me-dubai-1' 'eu-frankfurt-1' 'sa-saopaulo-1' 'ap-batam-1' 'ap-hyderabad-1' 'us-ashburn-1' 'ap-seoul-1' 'me-jeddah-1' 'af-johannesburg-1' 'ap-osaka-1' 'uk-london-1' 'eu-milan-1' 'eu-madrid-1' 'ap-melbourne-1' 'eu-marseille-1' 'mx-monterrey-1' 'il-jerusalem-1' 'ap-tokyo-1' 'us-chicago-1' 'us-phoenix-1' 'mx-queretaro-1' 'me-riyadh-1' 'sa-santiago-1' 'ap-singapore-1' 'us-sanjose-1' 'ap-sydney-1' 'sa-valparaiso-1' 'sa-vinhedo-1' 'ap-singapore-2' 'ap-chuncheon-1' 'ca-montreal-1' 'ca-toronto-1' 'eu-zurich-1')

  # Use getopt to parse options.
  local ARGS=$(getopt -o m:h:r:t:dA:f: --long mode:,hostname:,region:,tenant:,reboot-type:,announcement-id:,debug,dry-run,fault-domain: -n "$0" -- "$@")
  if [[ $? -ne 0 ]]; then
    _help
  fi
  eval set -- "$ARGS"

  while true; do
    case "$1" in
      -m|--mode)
        _mode="$2"
        shift 2
        ;;
      -h|--hostname)
        _vm_name="$2"
	_rescue_vm_name="rescue-${_vm_name}"
        shift 2
        ;;
      -f|--fault-domain)
        _fault_domain="$2"
        shift 2
        ;;
      -r|--region)
        _region="$2"
        local _match=''
        for _r in "${_supported_regions[@]}"; do
          if [[ "${_region}" == "${_r}" ]]; then
            _match=1
            break
          fi
        done
        if [[ -z "${_match}" ]]; then
          echo "Invalid region ${_region}. Supported regions: '${_supported_regions[@]}'"
          exit 1
        fi
	export OCI_CLI_REGION="${_region}"
        shift 2
        ;;
      -t|--tenant)
        _tenant="$2"
        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}"
        shift 2
        ;;
      --reboot-type)
        _reboot_type="$2"
        shift 2
        ;;
      -A|--announcement-id)
        _announcement_id="$2"
        shift 2
        ;;
      --dry-run)
        _dry_run=1
        shift
        ;;
      -d|--debug)
	set -x
        shift
	;;
      --)
        shift
        break
        ;;
      *)
        _help
        ;;
    esac
  done

  # Validate the mode.
  if [[ "${_mode}" != "rescue" ]] && [[ "${_mode}" != "unrescue" ]] && [[ "${_mode}" != "reboot" ]] && [[ "${_mode}" != "batch-reboot" ]] && [[ "${_mode}" != "fault-domain-update" ]]; then
    _help
  fi

  if [[ "${_mode}" == "reboot" ]] || [[ "${_mode}" == "batch-reboot" ]]; then
    if [[ -z "${_reboot_type}" ]]; then
      _help
    fi
  fi

  if [[ "${_mode}" == "fault-domain-update" ]]; then
    if [[ -z "${_fault_domain}" ]]; then
      echo "Error: --fault-domain is required for fault-domain-update mode."
      _help
    fi
  fi

  if [[ "${_mode}" == "batch-reboot" ]]; then
    if [[ -z "${_announcement_id}" ]]; then
      _help
    fi
  else
    if [[ -z "${_vm_name}" ]]; then
      _help
    fi
  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
  elif [[ "${_mode}" == "reboot" ]]; then
    echo "Performing reboot on ${_vm_name}..."
    _vm_reboot
  elif [[ "${_mode}" == "batch-reboot" ]]; then
    echo "Performing batch-reboot from announcement ${_announcement_id}..."
    _batch_reboot_from_announcement
  elif [[ "${_mode}" == "fault-domain-update" ]]; then
    echo "Performing fault domain update on ${_vm_name} to ${_fault_domain}..."
    _vm_fault_domain_update
  fi

  echo "Operation completed."
}

_log_message() {
    local _message="$@"
    local _timestamp=$(date +"%Y-%m-%d %H:%M:%S")
    local _log_file_name='oci_rescue_instance.log'
    local _log_file

    if [[ $EUID -eq 0 ]]; then
        _log_file="/var/log/${_log_file_name}"
        echo "[${_timestamp}] job_id: ${_job_id} user: ${_user} task: ${_message}" >> "${_log_file}"
        chgrp massfin "${_log_file}"
    else
        _log_file="$HOME/logs/${_log_file_name}"
        echo "[${_timestamp}] job_id: ${_job_id} user: ${_user} task: ${_message}" >> "${_log_file}"
    fi
}

function _help() {
  echo "Usage: $0 --tenant <tenant> --region <region> --mode <rescue|unrescue|reboot|batch-reboot|fault-domain-update> --hostname <hostname> [--reboot-type <RESET|SOFTRESET|DIAGNOSTICREBOOT>] [--announcement-id <ocid>] [--fault-domain <fd>] [--dry-run] [--debug]"
  echo "  batch-reboot: use --announcement-id instead of --hostname; requires --reboot-type."
  echo "  fault-domain-update: updates instance fault domain; requires --fault-domain."
  echo "  --tenant, -t: OCI tenant. '${_supported_tenants[@]}'"
  echo "  --region, -r: OCI region. '${_supported_regions[@]}'"
  echo "  --mode, -m: Mode (rescue, unrescue, reboot, batch-reboot, or fault-domain-update)."
  echo "  --reboot-type: Reboot type (RESET, SOFTRESET, or DIAGNOSTICREBOOT). Required for reboot and batch-reboot."
  echo "  --hostname, -h: Hostname to operate on (not used for batch-reboot)."
  echo "  --announcement-id, -A: OCI announcement OCID; lists instances to reboot (batch-reboot only)."
  echo "  --fault-domain, -f: Target fault domain (fault-domain-update only)."
  echo "  --dry-run: Preview instances to be rebooted without performing the action."
  echo "  --debug, -d: Enable debug mode."
  exit 1	
}

function _get_instances_from_announcement() {
  local _announcement_id="$1"
  oci announce announcements get --announcement-id "${_announcement_id}" \
    --raw-output \
    --query 'data."affected-resources"[?starts_with("resource-id", `ocid1.instance.`)].join(`\t`, ["resource-id", "resource-name" || "resource-id"]) | join(`\n`, @)' \
    2>/dev/null | sort -t $'\t' -k1,1 -u
}

function _batch_reboot_from_announcement() {
  if [[ "${_reboot_type}" != "RESET" ]] && [[ "${_reboot_type}" != "SOFTRESET" ]] && [[ "${_reboot_type}" != "DIAGNOSTICREBOOT" ]]; then
    echo "Invalid reboot type: ${_reboot_type}. Supported types: RESET, SOFTRESET, DIAGNOSTICREBOOT"
    exit 1
  fi

  local _lines
  _lines=$(_get_instances_from_announcement "${_announcement_id}") || exit 1

  if [[ -z "${_lines}" ]]; then
    echo "No compute instance OCIDs found in announcement affected-resources."
    exit 1
  fi

  local _ok=0 _fail=0 _total=0
  local _instance_id _disp

  while IFS=$'\t' read -r _instance_id _disp; do
    [[ -z "${_instance_id}" ]] && continue
    _total=$((_total + 1))
    
    if [[ -n "${_dry_run:-}" ]]; then
      echo "[DRY-RUN] Would reboot ${_disp} (${_instance_id}) with ${_reboot_type}..."
      continue
    fi

    if _instance_reboot; then
      _log_message "batch-reboot OK announcement ${_announcement_id} display ${_disp} instance ${_instance_id} state ${_lc_state}"
      _ok=$((_ok + 1))
      echo "  OK ${_disp}"
    else
      _log_message "batch-reboot FAIL announcement ${_announcement_id} display ${_disp} instance ${_instance_id}"
      _fail=$((_fail + 1))
      echo "  FAIL ${_disp}"
    fi
  done <<< "${_lines}"
  
  echo "Batch-reboot summary: ${_ok} succeeded, ${_fail} failed (total ${_total})."
  if [[ ${_fail} -gt 0 ]]; then
    exit 1
  fi
}

function _vm_reboot() {
  if [[ "${_reboot_type}" != "RESET" ]] && [[ "${_reboot_type}" != "SOFTRESET" ]] && [[ "${_reboot_type}" != "DIAGNOSTICREBOOT" ]]; then
    echo "Invalid reboot type: ${_reboot_type}. Supported types: RESET, SOFTRESET, DIAGNOSTICREBOOT"
    exit 1
  fi
  _compartment_info
  if [[ "${_compartment_id}" =~ ocid1.compartment ]]; then
    _vm_info
    if [[ "${_instance_id}" =~ ocid1.instance ]]; then
      echo "Rebooting ${_vm_name} with type ${_reboot_type}..."
      _instance_reboot
    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_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 _current_fault_domain _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].\"fault-domain\", data[0].\"lifecycle-state\"])" --raw-output) || true
}

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)
}

function _instance_reboot() {
  _log_message "Rebooting VM instance_id: ${_instance_id} with type: ${_reboot_type}"
  local _max_wait=300
  if [[ "${_reboot_type}" == "SOFTRESET" ]] || [[ "${_reboot_type}" == "DIAGNOSTICREBOOT" ]]; then
    _max_wait=960
  fi
  _lc_state=$(oci compute instance action --instance-id "${_instance_id}" --action "${_reboot_type}" --wait-for-state RUNNING --wait-interval-seconds 5 --max-wait-seconds "${_max_wait}" --query 'data."lifecycle-state"' --raw-output 2>&1) || return 1
}



function _work_request_status() {
  local _wr_id="$1"
  oci work-requests work-request get --work-request-id "${_wr_id}" --query 'data.status' --raw-output
}

function _vm_fault_domain_update() {
  _compartment_info
  if [[ "${_compartment_id}" =~ ocid1.compartment ]]; then
    _vm_info
    if [[ "${_instance_id}" =~ ocid1.instance ]]; then
      if [[ "${_lc_state}" != 'STOPPED' ]]; then
        echo "${_vm_name} current status: ${_lc_state}, expected status: STOPPED"
        exit 1
      fi
      if [[ "${_current_fault_domain}" == "${_fault_domain}" ]]; then
        echo "${_vm_name} already in fault domain: ${_fault_domain}"
        exit 1
      fi

      echo "Updating fault domain for ${_vm_name} from ${_current_fault_domain} to ${_fault_domain}..."
      local _work_request_id=$(oci compute instance update --instance-id "${_instance_id}" --fault-domain "${_fault_domain}" --force --query '"opc-work-request-id"' --raw-output)

      if [[ -z "${_work_request_id}" ]]; then
          echo "Failed to get work request ID for fault domain update."
          exit 1
      fi

      echo "Waiting for work request ${_work_request_id} to complete..."
      local _counter=0
      while true; do
        local _wr_status=$(_work_request_status "${_work_request_id}")
        if [[ "${_wr_status}" == "SUCCEEDED" ]]; then
          break
        elif [[ "${_wr_status}" == "FAILED" ]] || [[ "${_wr_status}" == "CANCELED" ]]; then
          echo "Work request ${_work_request_id} finished with status: ${_wr_status}"
          exit 1
        fi

        if [[ $_counter -gt 60 ]]; then
          echo "Timeout waiting for work request ${_work_request_id}"
          exit 1
        fi
        sleep 5
        _counter=$((_counter + 1))
      done

      echo "Starting VM: ${_vm_name}"
      _instance_start
      echo "${_vm_name} ${_lc_state}"

      _log_message "fault-domain-update OK: instance ${_instance_id} updated to ${_fault_domain}"
    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
}
_handle_host "$@"
