#!/usr/bin/env bash
# Copyright (c) 2023-2026 Tigera, Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

set -e

# Enable job control so that background processes get their own process groups.
set -m

my_dir="$(dirname $0)"
repo_dir="$my_dir/../.."
vm_name_prefix=$1
artifacts_dir="$repo_dir/artifacts"
# We bulk-create the VMs across all the zones in a region (based on available
# capacity) rather than pinning a single zone, so a single zone running out of
# capacity no longer blocks the job.  REGION selects the region; the zone each
# VM actually lands in is discovered after creation (see below).
region=${REGION:-europe-west3}
# Space-separated, in priority order.
: "${VM_MACHINE_TYPES:=n4-standard-4}"
: "${IMAGE_FAMILY:=ubuntu-minimal-2404-lts-amd64}"
: "${MAX_RUN_DURATION:=4h}"
disk_size=${VM_DISK_SIZE:-20GB}

source "$my_dir/ssh-options"
source "$my_dir/bulk-create-vms"
source "$my_dir/spot-vms"

# FV_STEP_TIMEOUT_MINUTES counts from here.
script_start=$(date +%s)

# shellcheck source=../../felix/.semaphore/batches.sh
source "$repo_dir/$COMPONENT/.semaphore/batches.sh"

all_batches=( "${batches[@]}" )
# Set for a lane that uses the memo, even when the memo is off for this run.
if [ -n "${BATCH_MEMO_LANE:-}" ]; then
  source "$my_dir/batch-memo"
fi
if [ -n "${BATCH_MEMO_PREFIX:-}" ]; then
  batch_memo_skip_cached "$artifacts_dir"
  if [ ${#batches[@]} -eq 0 ]; then
    batch_memo_record_lane "$artifacts_dir" "${all_batches[@]}"
    batch_memo_report "$artifacts_dir" "${#all_batches[@]}" 0
    echo "===== Every batch passed on an earlier run with the same inputs; exiting with RC=0 ====="
    exit 0
  fi
fi

###### Create the test VMs ######

names=""
for batch in "${batches[@]}"; do
  vm_name="$vm_name_prefix$batch"
  if [ -n "$names" ]; then
    names="$names,$vm_name"
  else
    names="$vm_name"
  fi
done

# Labels for the GCP instances.  These can only contain alphanumerics,
# dashes, underscores (so we can't just default to the semaphore job name).
# Sanitize the branch name to be compatible with GCP label requirements.
branch_label="${SEMAPHORE_GIT_BRANCH:-unknown}"
branch_label="$(echo "$branch_label" | tr '[:upper:]' '[:lower:]')"
branch_label="${branch_label//[^a-z0-9_-]/-}"
labels="ci-runner=true"
# Lets each CI system's sweeper find only its own VMs in the shared project.
labels+=",ci-system=${CI_SYSTEM:-semaphore}"
labels+=",ci-job-type=${CI_JOB_TYPE_LABEL:-${SEMAPHORE_GIT_REF_TYPE:-unknown}}"
labels+=",ci-group=${CI_GROUP_LABEL:-unknown}"
labels+=",ci-job=${CI_JOB_LABEL:-unknown}"
labels+=",ci-is-rerun=${SEMAPHORE_PIPELINE_RERUN:-false}"
labels+=",ci-branch=${branch_label}"
labels+=",ci-project=${CALICO_DIR_NAME}"
if [ -n "${SEMAPHORE_GIT_PR_NUMBER}" ]; then
  labels+=",ci-pr-number=${SEMAPHORE_GIT_PR_NUMBER}"
fi
if [ -n "${SEMAPHORE_WORKFLOW_ID}" ]; then
  labels+=",ci-workflow-id=${SEMAPHORE_WORKFLOW_ID}"
fi
if [ -n "${SEMAPHORE_JOB_ID}" ]; then
  labels+=",ci-job-id=${SEMAPHORE_JOB_ID}"
fi
if [ "${SEMAPHORE_WORKFLOW_TRIGGERED_BY_SCHEDULE}" = "true" ]; then
  labels+=",ci-scheduled=true"
else
  labels+=",ci-scheduled=false"
fi

# On ArgoCI, also add the labels ArgoCI puts on its own pods and VMs, so a
# billing report can find every machine a run paid for. The labels above stay
# as they are because the sweepers and existing dashboards rely on them.
label_value() {
  echo "$1" | tr '[:upper:]' '[:lower:]' | sed 's/[^a-z0-9_-]/-/g' | cut -c1-63 | sed 's/^[-_]*//; s/[-_]*$//'
}
add_label() {
  local v
  v=$(label_value "$2")
  if [ -n "$v" ]; then
    labels+=",$1=$v"
  fi
}
if [ -n "${CI_WORKFLOW_NAME:-}" ]; then
  labels+=",ci-provider=argoci"
  if [ -n "${CI_JOB_NAME:-}" ]; then
    add_label ci-ref-type job
  else
    add_label ci-ref-type "${CI_GIT_REF_TYPE:-}"
  fi
  add_label ci-step "${CI_STEP_NAME:-}"
  add_label ci-pipeline "${CI_PIPELINE_NAME:-}"
  add_label ci-cron "${CI_CRON_NAME:-}"
  if [ "${CI_GIT_REF_TYPE:-}" = "PR" ] || [ "${CI_GIT_REF_TYPE:-}" = "MERGE" ]; then
    add_label ci-author "${CI_GIT_AUTHOR:-}"
  fi
fi

# Instance labels don't carry over to the boot disk, so without this the disks
# are the one part of a VM's cost that can't be traced back to a run.
label_boot_disk() {
  gcloud --quiet compute disks add-labels "$1" --zone="$2" --labels="${labels}" ||
    echo "WARNING: could not label the boot disk of $1, its cost won't show against this run."
}

# Do a bulk create; this is faster and it saves API quota.  bulk_create_vms
# spreads the VMs across the region's zones by available capacity and picks the
# machine type.
#
# Shared with the replacement for a VM that fails to configure.
# shellcheck disable=SC2054 # the commas are gcloud's metadata separator
vm_create_args=(
       --service-account="semaphore-v2-gcr@unique-caldron-775.iam.gserviceaccount.com"
       --scopes="https://www.googleapis.com/auth/cloud-platform"
       --image-family="${IMAGE_FAMILY}"
       --image-project=ubuntu-os-cloud
       --boot-disk-size="$disk_size"
       --max-run-duration="${MAX_RUN_DURATION}"
       --instance-termination-action=DELETE
       --labels="${labels}"
       --metadata-from-file startup-script="$my_dir/vm-bootstrap.sh"
       --metadata block-project-ssh-keys=TRUE,ssh-keys="ubuntu:$(ssh-keygen -y -f "$HOME/.ssh/id_rsa")",enable-guest-attributes=TRUE
)
vm_base_create_args=( "${vm_create_args[@]}" )

mkdir -p "$artifacts_dir"
capacity_scores_file="$artifacts_dir/.capacity-scores"
rm -f "$capacity_scores_file"
if [ "${VM_PROVISIONING_MODEL:-STANDARD}" = SPOT ]; then
  echo "Recording spot capacity scores (record only; nothing acts on them)..."
  # shellcheck disable=SC2086 # a space-separated list
  record_capacity_scores "$region" "${#batches[@]}" "$capacity_scores_file" \
    ${VM_SPOT_MACHINE_TYPES:-$VM_MACHINE_TYPES}
fi

fleet_created=$(date +%s)
bulk_create_vms "$names" "$region" "${vm_create_args[@]}"
vm_create_args+=( --machine-type="$vm_machine_type" --boot-disk-type="$vm_boot_disk_type" )
if [ "$vm_provisioning_model" = SPOT ]; then
  vm_create_args+=( --provisioning-model=SPOT --labels=ci-provisioning=spot )
else
  vm_create_args+=( --labels=ci-provisioning=standard )
fi

# Each VM's own score depends on its zone, which the bulk create picks.
label_capacity() {
  local cap_labels
  cap_labels="$(capacity_labels "$capacity_scores_file" "$3" "$2")"
  [ -n "$cap_labels" ] || return 0
  gcloud --quiet compute instances add-labels "$1" --zone="$2" --labels="$cap_labels" ||
    echo "WARNING: could not add the capacity-score labels to $1."
}

# Since the VMs are spread across the region's zones, we can no longer assume a
# single zone for the downstream describe/ssh/delete commands.  Build a
# name->zone map by listing the instances we just created, filtered by our
# workflow-unique name prefix.  bulk_create_vms waits for the instances to
# exist.
echo "Discovering which zone each VM landed in..."
declare -A vm_zone
while IFS=, read -r name vm_z; do
  [ -n "$name" ] || continue
  vm_zone["$name"]="$vm_z"
  echo "  $name -> $vm_z"
done < <(gcloud --quiet compute instances list \
              --filter="name~'^${vm_name_prefix}'" \
              --format='csv[no-heading](name,zone.basename())')

# Fail fast if any expected VM is missing from the map; the rest of the script
# relies on knowing every VM's zone.  A spot VM already preempted is found by
# its preemption, and its batch retries it like any other.
for batch in "${batches[@]}"; do
  vm_name="$vm_name_prefix$batch"
  [ -z "${vm_zone[$vm_name]:-}" ] || continue
  if [ "$vm_provisioning_model" = SPOT ] &&
    preempted="$(vm_preempted "$vm_name" "$fleet_created" region "$region")"; then
    vm_zone["$vm_name"]="${preempted#* }"
    echo "  $vm_name -> ${preempted#* } (spot VM already preempted; its batch will rerun on demand)"
    continue
  fi
  echo "ERROR: could not determine the zone of VM $vm_name after bulk create." 1>&2
  exit 1
done

# Each gcloud takes ~100MB; one or two per VM at once ran a 61-VM lane's 8GB
# Semaphore agent out of memory and killed the job's shell.  Anything but a
# positive integer would spin the loop below (0) or lift the cap (non-number).
[[ "${VM_LABEL_PARALLELISM:-}" =~ ^[1-9][0-9]*$ ]] || VM_LABEL_PARALLELISM=8
for vm_name in "${!vm_zone[@]}"; do
  while [ "$(jobs -rp | wc -l)" -ge "$VM_LABEL_PARALLELISM" ]; do
    wait -n || true
  done
  # One job per VM, so a spot VM's two labels count once against the cap.
  {
    label_boot_disk "$vm_name" "${vm_zone[$vm_name]}"
    if [ "$vm_provisioning_model" = SPOT ]; then
      label_capacity "$vm_name" "${vm_zone[$vm_name]}" "$vm_machine_type"
    fi
  } &
done
wait

###### Configure VMs, run tests and shut them down ######

log_monitor_regexps=(
  "(?<!Decode)Failure"
  "SUCCESS"
  "PASSED"
  "Parallel test node"
  "Test batch"
  "FV-TEST-START"
  "^test.*\.\.\. ok"
  "\.\.\. ERROR$"
  "Failure output:"
  "^ERROR:"
  "^Traceback"
  "^FAILED"
  "^OK$"
  "^XML:"
  "^\[success\]"
  "^\[error\]"
  "RUNNER:"
)

# Combine the regexps; in Perl mode, grep only supports one
# pattern so we combine them with '|'.
monitor_pattern=""
for r in "${log_monitor_regexps[@]}"; do
  monitor_pattern="${monitor_pattern}|$r"
done
monitor_pattern="${monitor_pattern:1}" # Strip leading '|'

test_pid=()
watchdog_pids=()
monitor_pids=()
log_files=()

# Calculate watchdog timeout before starting batches.
# JOB_TIMEOUT_MINUTES can be set to match the Semaphore execution_time_limit;
# the watchdog fires 5 minutes before that to leave time for cleanup.
: "${JOB_TIMEOUT_MINUTES:=60}"
if [ "$JOB_TIMEOUT_MINUTES" -le 5 ] 2>/dev/null; then
  echo "WARNING: JOB_TIMEOUT_MINUTES ($JOB_TIMEOUT_MINUTES) is too low for watchdog, disabling."
  watchdog_seconds=0
else
  watchdog_seconds=$(( (JOB_TIMEOUT_MINUTES - 5) * 60 ))
fi

# attempt_deadline <attempt start epoch> prints when the watchdog kills that
# attempt: a retry gets a fresh JOB_TIMEOUT_MINUTES, but never past the step's
# own deadline, less time for the watchdog's captures, the summary and the
# step's epilogue.
attempt_deadline() {
  # With the watchdog off, only the step deadline limits an attempt.
  local deadline=$(( $1 + 365 * 24 * 3600 )) step_deadline
  [ "$watchdog_seconds" -le 0 ] || deadline=$(( $1 + watchdog_seconds ))
  if [ -n "${FV_STEP_TIMEOUT_MINUTES:-}" ]; then
    step_deadline=$(( script_start + (FV_STEP_TIMEOUT_MINUTES - 15) * 60 ))
    [ "$step_deadline" -ge "$deadline" ] || deadline=$step_deadline
  fi
  echo "$deadline"
}

# write_watchdog_file <file> <attempt start> <provisioning model> <created
# epoch> <machine type> tells the batch's watchdog when to fire and what the
# VM is.  Replaced whole so the watchdog never reads half of it.
write_watchdog_file() {
  echo "$(attempt_deadline "$2") $2 $3 $4 $5" >"$1.tmp" && mv "$1.tmp" "$1"
}

# A preempted batch reruns only if the step has time for the preemption check
# (2 min), the wait for GCE to delete the VM (5 min), creating and setting up
# its replacement (~5 min), and a full batch.  The batch memo keeps no timings,
# so a full batch is taken as 40 min: the slowest lane took 38 on 24 Nov 2026.
preempt_retry_overhead_seconds=$(( 12 * 60 ))
preempt_retry_batch_seconds=$(( 40 * 60 ))

# Format batch name for log files: zero-pad numeric values to 3 digits
format_batch_for_log() {
  local batch="$1"
  # Check if batch is a number
  if [[ "$batch" =~ ^[0-9]+$ ]]; then
    printf "%03d" "$batch"
  else
    echo "$batch"
  fi
}

# The functions below run inside a batch's subshell and share its variables.

# check_spot_failure [<failed epoch>] sets spot_check to preempted, after-failure (preempted, but
# only once the failure had happened, so not its cause), not or check-failed,
# and preempt_at.  Only a VM created as spot can have been preempted.
check_spot_failure() {
  spot_check=not
  preempt_at=""
  [ "$attempt_model" = SPOT ] || return 0
  local check_rc=0 failed="${1:-$(date +%s)}"
  echo "$prefix Checking whether GCE preempted spot VM $vm_name..."
  preempt_at="$(vm_preemption_check "$vm_name" "$zone" "$attempt_created" "$failed")" || check_rc=$?
  # The latest check settles whether a failure may have been a preemption.
  check_failed=false
  case "$check_rc" in
    0)
      # The check polls past the failure, so it can see a later preemption.
      # Within the 30s soft shutdown the preemption may still be the cause.
      if [ "$(date -d "$preempt_at" +%s 2>/dev/null || echo 0)" -gt $((failed + 30)) ]; then
        spot_check=after-failure
        echo "$prefix Spot VM $vm_name was preempted at $preempt_at, after the failure; not its cause."
      else
        spot_check=preempted
        echo "$prefix Spot VM $vm_name was PREEMPTED at $preempt_at."
      fi
      ;;
    2)
      spot_check=check-failed
      check_failed=true
      echo "$prefix Could not ask GCE whether spot VM $vm_name was preempted; handling the failure as usual, without a retry."
      ;;
    *) echo "$prefix Spot VM $vm_name was not preempted." ;;
  esac
}

# run_batch_attempt sets rc and attempt_result: pass, fail, or preempted.  Only
# a confirmed preemption cuts the attempt short, since the VM and its results
# are already gone; anything else gets the usual collection and teardown.
run_batch_attempt() {
  local attempt configured=false collected=true
  rc=1
  attempt_result=fail
  check_failed=false
  for attempt in $(seq 1 "$VM_CONFIGURE_ATTEMPTS"); do
    echo "$prefix Configuring test VM $vm_name (attempt $attempt). Redirecting log to $conf_log_file."
    if env ZONE="$zone" "${my_dir}/configure-test-vm" "$vm_name" >> "$conf_log_file" 2>&1; then
      configured=true
      break
    fi
    # A preemption must not use up a setup attempt.  A failure dated past the
    # shutdown window lets a RUNNING VM end the check at once; missing a
    # preemption here costs only a setup attempt, as the VM is recreated anyway.
    check_spot_failure "$(( $(date +%s) - 60 ))"
    if [ "$spot_check" = preempted ]; then
      attempt_result=preempted
      return
    fi
    [ "$attempt" -lt "$VM_CONFIGURE_ATTEMPTS" ] || break
    echo "$prefix Configuration of VM $vm_name FAILED; replacing it with a fresh VM."
    echo "===== attempt $attempt failed; replacing $vm_name =====" >> "$conf_log_file"
    gcloud --quiet beta compute instances delete "$vm_name" --zone="$zone" --no-graceful-shutdown >> "$conf_log_file" 2>&1
    # A spot VM GCE may be deleting would collide with the recreate's name.
    if [ "$spot_check" != not ]; then
      vm_wait_gone "$vm_name" "$zone" 300 || echo "$prefix VM $vm_name is still being deleted; recreating anyway."
    fi
    attempt_created=$(date +%s)
    check_failed=false
    if ! gcloud --quiet compute instances create "$vm_name" --zone="$zone" "${attempt_args[@]}" >> "$conf_log_file" 2>&1; then
      # The zone may be out of spot; on demand is still worth a try.
      if [ "$attempt_model" = SPOT ] &&
        retry_type="$(create_on_demand_replacement "$vm_name" "$zone" "$attempt_type" \
          "${vm_base_create_args[@]}" --labels=ci-provisioning=standard,ci-spot-fallback=true 2>>"$conf_log_file")"; then
        echo "$prefix No spot replacement for $vm_name; replaced it with on-demand ${retry_type}."
        attempt_model=STANDARD
        attempt_type="$retry_type"
        # shellcheck disable=SC2054 # the comma is gcloud's label separator
        attempt_args=( "${vm_base_create_args[@]}" --machine-type="$retry_type"
          --boot-disk-type="$(boot_disk_type_for "$retry_type")" --labels=ci-provisioning=standard,ci-spot-fallback=true )
      else
        echo "$prefix Could not create a replacement for $vm_name."
        break
      fi
    fi
    label_boot_disk "$vm_name" "$zone" >> "$conf_log_file" 2>&1
    if [ "$attempt_model" = SPOT ]; then
      label_capacity "$vm_name" "$zone" "$attempt_type" >> "$conf_log_file" 2>&1
    fi
    # vm-ip caches by name and zone, both of which the replacement reuses.
    rm -f "/tmp/vm_ip_${vm_name}_${zone}"
    vm_ip="$(env VM_NAME="$vm_name" ZONE="$zone" "$my_dir/vm-ip")"
    write_watchdog_file "$watchdog_file" "$attempt_start" "$attempt_model" "$attempt_created" "$attempt_type"
  done
  if [ "$configured" = true ]; then
    echo "$prefix Configuration of VM $vm_name SUCCEEDED."
  else
    echo "$prefix Configuration of VM $vm_name FAILED.  Log file will be uploaded as artifact $conf_log_file. "
    [ "$check_failed" = false ] || report_check_failed
    return
  fi

  echo "$prefix Test batch $batch STARTING (sending logs to $log_file)..."
  if [ "$attempt_model" = SPOT ]; then
    maybe_simulate_preemption "$batch" "$vm_name" "$zone" 2>&1 | sed "s/^/$prefix /"
  fi
  run_batch "$my_dir/on-test-vm" "$batch" "$vm_name" "$log_file"
  rc=$?
  if [ $rc != 0 ]; then
    # The step log follows this batch's log with a 1s-polling tail; let it print
    # the attempt's last lines before anything about how the attempt ended.
    sleep 2
    # The verdict can reach us a poll after the tests end, by which time a
    # preemption may have followed a genuine failure.
    check_spot_failure "$(stat -c %Y "$log_file" 2>/dev/null || date +%s)"
    if [ "$spot_check" = preempted ]; then
      attempt_result=preempted
      return
    fi
    [ "$spot_check" != after-failure ] || write_preempt_record genuine-fail
  fi
  if [ $rc = 0 ]; then
    echo "$prefix Test batch $batch SUCCEEDED."
  else
    mv "$log_file" "$failed_log_file"
    echo "$prefix Test batch $batch FAILED.  Log file will be uploaded as artifact $failed_log_file."
    # Upload alongside the fv-artifacts in GCS (GCS_WORKFLOW_DIR), via gcloud.
    if [ -n "${GCS_WORKFLOW_DIR:-}" ] && [ -n "${COMPONENT:-}" ]; then
      failed_log_upload_dir="${GCS_WORKFLOW_DIR}/${COMPONENT}/failed-fv-logs"
      if [ -n "${JOB_TAG:-}" ]; then
        failed_log_upload_dir="${failed_log_upload_dir}/${JOB_TAG}"
      fi
      gcloud storage cp "$failed_log_file" "${failed_log_upload_dir}/" || true
    fi
  fi

  # The SSH-based teardown steps below are wrapped in 'timeout': if the VM
  # wedged (e.g. a kernel BPF/vmap teardown deadlock that leaves it
  # SSH-unreachable), these would otherwise hang until the watchdog kills the
  # whole batch.  Bounding them lets a batch whose tests already finished
  # proceed straight to the (control-plane) VM delete.  gcloud delete does not
  # need SSH, so it reclaims a wedged VM regardless.
  collect_log_file="$artifacts_dir/collect-artifacts-$batch_formatted.log"
  if timeout 180 "${ssh_cmd[@]}" COMPONENT="${COMPONENT}" "${CALICO_DIR_NAME}/.semaphore/collect-artifacts" >& "$collect_log_file"; then
    echo "$prefix Remote artifact collection SUCCEEDED"
  else
    echo "$prefix Remote artifact collection FAILED (rc=$?)"
    collected=false
  fi
  if timeout 180 scp "${SSH_OPTIONS[@]}" -r -C "ubuntu@${vm_ip}:${CALICO_DIR_NAME}/artifacts" "${repo_dir}/artifacts/${batch}" >> "$collect_log_file" 2>&1; then
    echo "$prefix Artifact retrieval SUCCEEDED"
  else
    echo "$prefix Artifact retrieval FAILED (rc=$?)"
    collected=false
  fi
  if [ "$collected" = false ]; then
    check_spot_failure
    if [ "$spot_check" != not ] && [ "$spot_check" != check-failed ] && [ $rc != 0 ]; then
      # The tests had already failed, so this is a genuine failure.
      echo "$prefix Batch $batch had already FAILED when its VM was preempted; not retrying."
      write_preempt_record genuine-fail
    elif [ "$spot_check" = preempted ]; then
      # A rerun could only turn a pass into a flaky failure.
      echo "$prefix Test batch $batch SUCCEEDED, but its artifacts went with the preempted VM; not rerunning."
      write_preempt_record passed-uncollected
    fi
  fi

  echo "$prefix Deleting test VM $vm_name"
  if timeout 300 gcloud --quiet beta compute instances delete "$vm_name" --zone="${zone}" --no-graceful-shutdown; then
    echo "$prefix Deletion of test VM $vm_name SUCCEEDED"
  else
    echo "$prefix Deletion of test VM $vm_name FAILED, will retry at end of job. "
  fi
  if [ $rc = 0 ]; then
    attempt_result=pass
  elif [ "$check_failed" = true ]; then
    report_check_failed
  fi
}

# write_preempt_record <outcome> records the batch's FV-PREEMPT fields, which
# the end-of-run summary reports.
write_preempt_record() {
  echo "run=$(spot_run_id) lane=$(spot_lane_id) batch=${batch} vm=${vm_name} type=${attempt_type} zone=${zone} at=${preempt_at:-unknown} outcome=$1" \
    > "$preempt_file"
}

# report_check_failed marks a failed batch as a possible preemption, so it is
# never an unexplained failure.
report_check_failed() {
  local report_type=fv why="GCE could not be asked whether spot VM ${vm_name} (${attempt_type}) was preempted, so the batch was not retried; treat this failure as a possible preemption."
  [ "$batch" != ut ] || report_type=ut
  preempt_at=""
  write_preempt_record check-failed
  echo "===== ${why} =====" >> "$conf_log_file"
  if [ -f "$failed_log_file" ]; then
    echo "===== ${why} =====" >> "$failed_log_file"
  fi
  write_preemption_junit "$artifacts_dir/$batch/report/felix_${report_type}_preempted_${batch_formatted}.xml" \
    "$batch" "batch ${batch}: spot VM preemption check failed (${zone})" "$why"
}

# set_aside_preempted_logs keeps the preempted attempt's logs under names the
# failure analyser doesn't read: it only looks at -FAILED batch logs, and falls
# back to the configure log, which must be the retry's.
set_aside_preempted_logs() {
  [ ! -f "$log_file" ] || mv "$log_file" "$artifacts_dir/test-$batch_formatted-PREEMPTED.log"
  [ ! -f "$conf_log_file" ] || mv "$conf_log_file" "$artifacts_dir/configure-vm-$batch_formatted-PREEMPTED.log"
}

# find_preempt_retry_blocker sets blocker to why a preempted batch can't rerun
# on demand (an FV-PREEMPT outcome), or to nothing if it can.  When it can, the
# on-demand replacement exists on return, and retry_type holds its type.
find_preempt_retry_blocker() {
  local remaining
  blocker=""
  if [ "${VM_PREEMPT_RETRIES:-1}" = 0 ] || [ -z "${FV_STEP_TIMEOUT_MINUTES:-}" ]; then
    blocker=retries-off
    return
  fi
  # Measured to the watchdog's deadline, not the step's: the retry gets no more.
  remaining=$(( $(attempt_deadline "$(date +%s)") - $(date +%s) ))
  if [ "$remaining" -lt $(( preempt_retry_overhead_seconds + preempt_retry_batch_seconds )) ]; then
    blocker=no-time
    return
  fi
  # The retry's deadline starts now: the preempted attempt's could fire while
  # the replacement is still being made.
  write_watchdog_file "$watchdog_file" "$(date +%s)" STANDARD "$(date +%s)" "$attempt_type"
  echo "$prefix Waiting for GCE to finish deleting preempted VM $vm_name..."
  if ! vm_wait_gone "$vm_name" "$zone" 300; then
    blocker=delete-timeout
    return
  fi
  attempt_created=$(date +%s)
  # shellcheck disable=SC2054 # the comma is gcloud's label separator
  if ! retry_type="$(VM_REPLACE_DEADLINE=$(( $(attempt_deadline "$(date +%s)") - preempt_retry_batch_seconds - 300 )) \
    create_on_demand_replacement "$vm_name" "$zone" "$attempt_type" "${vm_base_create_args[@]}" \
    --labels=ci-provisioning=standard,ci-preempt-retry=true 2>>"$conf_log_file.retry")"; then
    blocker=no-capacity
  fi
}

# fail_preempted_batch <outcome> reports a preemption the batch can't recover
# from and ends the batch.
fail_preempted_batch() {
  local outcome="$1" why report_type=fv name
  [ "$batch" != ut ] || report_type=ut
  case "$outcome" in
    retries-off) why="Retries are off: VM_PREEMPT_RETRIES is 0 or FV_STEP_TIMEOUT_MINUTES is unset." ;;
    no-time) why="Not retried: the step has too little time left for a rerun." ;;
    delete-timeout) why="Not retried: GCE was still deleting the preempted VM after 5 minutes." ;;
    no-capacity) why="Not retried: no on-demand VM could be created in ${zone}." ;;
  esac
  name="batch ${batch}: spot VM preempted at ${preempt_at} (${zone})"
  if [ -f "$conf_log_file.retry" ]; then
    cat "$conf_log_file.retry" >> "$conf_log_file"
    rm -f "$conf_log_file.retry"
  fi
  set_aside_preempted_logs
  echo "$prefix Test batch $batch FAILED: ${name}. ${why}"
  write_preempt_record "$outcome"
  write_preemption_junit "$artifacts_dir/$batch/report/felix_${report_type}_preempted_${batch_formatted}.xml" \
    "$batch" "$name" "Spot VM ${vm_name} (${attempt_type}). ${why}"
  touch "$done_marker"
  exit 1
}

for batch in "${batches[@]}"; do
  vm_name="$vm_name_prefix$batch"
  # Each VM may be in a different zone; look up the one it landed in.  Every
  # downstream command in this iteration (vm-ip, on-test-vm, configure-test-vm,
  # the delete, and the watchdog's serial/snapshot capture) uses $zone.  We also
  # export ZONE: run_batch (sourced from batches.sh) shells out to
  # 'gcloud get-serial-port-output --zone="${ZONE}"' to grab the serial console
  # when a VM wedges, and it reads ZONE from the environment.  The backgrounded
  # per-batch subshell below captures this value at fork time, so each batch
  # sees its own VM's zone.
  zone="${vm_zone[$vm_name]}"
  export ZONE="$zone"
  if [ "$vm_provisioning_model" = SPOT ]; then
    # A preempted spot VM is gone; its batch finds out why and retries.
    vm_ip="$(env VM_NAME="$vm_name" ZONE="$zone" "$my_dir/vm-ip")" || vm_ip=""
  else
    vm_ip="$(env VM_NAME="$vm_name" ZONE="$zone" "$my_dir/vm-ip")"
  fi
  batch_formatted="$(format_batch_for_log "$batch")"
  log_file="$artifacts_dir/test-$batch_formatted.log"
  failed_log_file="$artifacts_dir/test-$batch_formatted-FAILED.log"
  ssh_cmd=( env "VM_NAME=$vm_name" "ZONE=$zone" "$my_dir/on-test-vm" )
  prefix="[batch=${batch}]"
  touch "$log_file"

  preempt_file="$artifacts_dir/.batch-${batch_formatted}.preempt"
  watchdog_file="$artifacts_dir/.batch-${batch_formatted}.watchdog"
  rm -f "$preempt_file"
  batch_start=$(date +%s)
  write_watchdog_file "$watchdog_file" "$batch_start" "$vm_provisioning_model" "$fleet_created" "$vm_machine_type"

  # Run the configuration, test, and, teardown in a subshell so we can
  # background it.
  (
    set +e

    # Tell the watchdog (below) when this batch has fully finished, so it can
    # distinguish "done, just waiting to be reaped" from "genuinely hung".
    done_marker="$artifacts_dir/.batch-${batch_formatted}.done"
    rm -f "$done_marker"
    trap 'touch "$done_marker"' EXIT

    # A VM that fails to boot is usually a bad instance, so a fresh one gets a
    # second try. It keeps the name and zone, which everything else tracks it by.
    : "${VM_CONFIGURE_ATTEMPTS:=2}"
    conf_log_file="$artifacts_dir/configure-vm-$batch_formatted.log"
    attempt_model="$vm_provisioning_model"
    attempt_type="$vm_machine_type"
    attempt_created="$fleet_created"
    attempt_start="$batch_start"
    attempt_args=( "${vm_create_args[@]}" )
    retried=false
    : > "$conf_log_file"
    while true; do
      run_batch_attempt
      [ "$attempt_result" = preempted ] || break
      find_preempt_retry_blocker
      [ -z "$blocker" ] || fail_preempted_batch "$blocker"

      # The replacement is on demand, so it can't be preempted in turn.
      echo "$prefix Retrying batch $batch on on-demand ${retry_type} VM $vm_name in $zone."
      set_aside_preempted_logs
      mv "$conf_log_file.retry" "$conf_log_file"
      # Only the retry's results count.
      rm -rf "${artifacts_dir:?}/${batch}"
      echo "RUNNER: This is a rerun on an on-demand VM: the spot VM that first ran batch '$batch' was preempted at ${preempt_at} (${zone})." > "$log_file"
      write_preempt_record retried
      attempt_model=STANDARD
      attempt_type="$retry_type"
      # shellcheck disable=SC2054 # the comma is gcloud's label separator
      attempt_args=( "${vm_base_create_args[@]}" --machine-type="$retry_type"
        --boot-disk-type="$(boot_disk_type_for "$retry_type")"
        --labels=ci-provisioning=standard,ci-preempt-retry=true )
      retried=true
      label_boot_disk "$vm_name" "$zone"
      rm -f "/tmp/vm_ip_${vm_name}_${zone}"
      vm_ip="$(env VM_NAME="$vm_name" ZONE="$zone" "$my_dir/vm-ip")"
      attempt_start=$(date +%s)
      write_watchdog_file "$watchdog_file" "$attempt_start" STANDARD "$attempt_created" "$attempt_type"
    done
    if [ "$retried" = true ]; then
      if [ "$rc" = 0 ]; then
        sed -i 's/outcome=retried$/outcome=retried-pass/' "$preempt_file"
      else
        sed -i 's/outcome=retried$/outcome=retried-fail/' "$preempt_file"
      fi
    fi
    # Whatever reports a preempted collection left are partial.
    if [ $rc = 0 ] && [ -n "${BATCH_MEMO_PREFIX:-}" ] && ! grep -qs 'outcome=passed-uncollected$' "$preempt_file"; then
      batch_memo_record "$artifacts_dir" "$batch"
    fi

    # Mark the batch fully complete so the watchdog skips snapshot/kill for it.
    touch "$done_marker"
    exit $rc
  ) &
  pid=$!

  log_files+=( "$log_file" )
  test_pid+=( "$pid" )

  # Start a per-batch watchdog that kills this batch before the Semaphore job
  # timeout.  The watchdog only acts if the batch is genuinely still running
  # (checked via a marker file, see below), so a batch that finished early but
  # hasn't been reaped yet by the sequential wait loop does not get a spurious
  # timeout report.  Each batch also kills its own watchdog when it is reaped
  # (in the wait loop below), so there is no PID-reuse race.
  if [ "$watchdog_seconds" -gt 0 ]; then
  (
    # Distinguish a genuinely hung batch from one that has merely finished but
    # not yet been reaped by the sequential loop below.  We use a marker file
    # rather than 'kill -0 $pid' because a finished-but-unreaped batch is a
    # zombie whose pid still exists, so kill -0 would wrongly report it alive
    # and we would emit a spurious timeout report for a batch that passed.
    batch_formatted="$(format_batch_for_log "$batch")"
    done_marker="$artifacts_dir/.batch-${batch_formatted}.done"
    # Polled, not slept, because a preemption retry moves the deadline.
    while true; do
      while true; do
        [ ! -f "$done_marker" ] || exit 0
        read -r wd_deadline wd_start wd_model wd_created wd_type < "$watchdog_file"
        [ "$(date +%s)" -lt "$wd_deadline" ] || break
        sleep 15
      done
      # A hung spot batch may really be a preempted one.  Its VM isn't failing
      # afresh, so a VM still RUNNING settles the check at once.
      wd_preempt_at=""
      if [ "$wd_model" = SPOT ] && [ ! -s "$preempt_file" ] &&
        wd_preempt_at="$(vm_preemption_check "$vm_name" "$zone" "$wd_created" $(( $(date +%s) - 60 )))"; then
        # The batch may have settled the preemption itself during the check:
        # finished, recorded an outcome, or begun its retry.
        [ ! -f "$done_marker" ] || exit 0
        if [ -s "$preempt_file" ]; then
          wd_preempt_at=""
          break
        fi
        read -r _ wd_now_start _ < "$watchdog_file"
        [ "$wd_now_start" = "$wd_start" ] || continue
      else
        wd_preempt_at=""
      fi
      break
    done
    wd_elapsed=$(( $(date +%s) - wd_start ))
    wd_limit="job timeout ${JOB_TIMEOUT_MINUTES}m"
    [ "$wd_deadline" -ge $(( wd_start + watchdog_seconds )) ] ||
      wd_limit="step deadline, FV_STEP_TIMEOUT_MINUTES ${FV_STEP_TIMEOUT_MINUTES}m"
    if [ "$batch" = "ut" ]; then
      report_type="ut"
    else
      report_type="fv"
    fi

    echo
    echo "===== WATCHDOG: batch $batch approaching its deadline (${wd_limit}) ====="

    if [ -n "$wd_preempt_at" ]; then
      echo "  Spot VM $vm_name was PREEMPTED at $wd_preempt_at; killing batch $batch (pid $pid)"
      # Recorded before the kill, because reaping the batch kills this watchdog
      # too.  The logs are set aside after the reap, once nothing writes them.
      echo "run=$(spot_run_id) lane=$(spot_lane_id) batch=${batch} vm=${vm_name} type=${wd_type} zone=${zone} at=${wd_preempt_at} outcome=watchdog" \
        > "$preempt_file"
      write_preemption_junit "$artifacts_dir/$batch/report/felix_${report_type}_preempted_${batch_formatted}.xml" \
        "$batch" "batch ${batch}: spot VM preempted at ${wd_preempt_at} (${zone})" \
        "Spot VM ${vm_name} (${wd_type}). Not retried: the batch hung after the preemption until the watchdog killed it."
      kill -TERM "-$pid" 2>/dev/null || true
      echo "==============================================================="
      exit 0
    fi

    # 1. Serial console via the GCP control plane.  This does not use the VM's
    # network/SSH path, so it still works when the VM is wedged and SSH would
    # return rc=255 -- exactly the case that matters most (kernel soft-lockup /
    # OOM / oops).  The kernel logs to ttyS0 (console=ttyS0), so a hang shows up
    # here even when the in-VM snapshot below cannot connect.
    serial_log="$artifacts_dir/vm-serial-$batch_formatted.log"
    echo "  Capturing VM serial console to $serial_log"
    timeout 60 gcloud --quiet compute instances get-serial-port-output "$vm_name" \
        --zone="$zone" --port=1 \
        > "$serial_log" 2>&1 \
        || echo "  Serial console capture failed/timed out (rc=$?)"

    # 2. SSH-based in-VM snapshot (ps/bpftool/bpffs/dmesg/kernel stacks).  Useful
    # when the VM is merely slow rather than wedged.  Wrapped in 'timeout' so a
    # hung VM/SSH cannot extend the kill.
    snapshot_log="$artifacts_dir/vm-snapshot-$batch_formatted.log"
    echo "  Capturing pre-kill VM snapshot to $snapshot_log"
    timeout 60 env VM_NAME="$vm_name" ZONE="$zone" "$my_dir/on-test-vm" \
        bash "$CALICO_DIR_NAME/.semaphore/vms/vm-snapshot" \
        > "$snapshot_log" 2>&1 \
        || echo "  VM snapshot capture failed/timed out (rc=$?)"

    # Push the diagnostics immediately.  A job killed at its timeout may never
    # run publish-artifacts (or have it truncated mid-upload), and these files
    # sort after test-*.log alphabetically, so they would be the first dropped.
    # Pushing by basename from $artifacts_dir keeps the remote path tidy.
    # The watchdog is always the first pusher of these files (publish-artifacts
    # runs later in the epilogue), so no --force/overwrite is needed here.
    for diag in "$serial_log" "$snapshot_log"; do
      [ -s "$diag" ] || continue
      ( cd "$artifacts_dir" && artifact push job "$(basename "$diag")" ) \
          >/dev/null 2>&1 || true
    done

    echo "  Killing hung batch $batch (pid $pid)"
    kill -TERM "-$pid" 2>/dev/null || true

    # Generate a JUnit XML report for the timed-out batch so it shows up
    # in Semaphore test results as a clear failure.
    report_dir="$artifacts_dir/$batch/report"
    mkdir -p "$report_dir"
    cat > "$report_dir/felix_${report_type}_timeout_${batch_formatted}.xml" <<JUNIT_EOF
<?xml version="1.0" encoding="UTF-8"?>
<testsuites>
  <testsuite name="batch-${batch}" tests="1" failures="1" errors="0" time="$wd_elapsed">
    <testcase name="batch ${batch} completion" classname="ci.watchdog" time="$wd_elapsed">
      <failure message="Batch ${batch} timed out after ${wd_elapsed}s (${wd_limit})">
The watchdog killed batch ${batch} because it was still running as it neared
its deadline (${wd_limit}). Check the batch log file
for details on which test was hung.
      </failure>
    </testcase>
  </testsuite>
</testsuites>
JUNIT_EOF
    echo "==============================================================="
  ) &
  watchdog_pids+=( "$!" )
  else
    watchdog_pids+=( "" )
  fi

  (
    # Redirect tail's stdin from /dev/null to prevent waiting
    # forever on reads in semaphore CI.  Follows the name: a preemption retry
    # sets the first log aside and starts a new one.
    tail -F "$log_file" < /dev/null 2>/dev/null | \
      grep --line-buffered --perl "${monitor_pattern}" -B 2 -A 15 | \
      sed 's/.*/'"${prefix}"' &/' | \
      grep --perl --line-buffered -v '^\[batch=[^\]]+\]\s+$';
  ) &
  mon_pid=$!
  monitor_pids+=( "$mon_pid" )
done

final_result=0

# Give the batches time to emit their start-up logs.
sleep 5
echo
echo "===== Waiting for background test runners to finish ===="
echo

summary=()
preempt_lines=()
preempt_retried_pass=0
preempt_retried_fail=0
preempt_not_retried=0
preempt_check_failed=0
preempt_after_failure=0
batch_outcomes_file="$artifacts_dir/.batch-outcomes"
: > "$batch_outcomes_file"
for i in "${!batches[@]}"; do
  batch=${batches[$i]}
  pid=${test_pid[$i]}
  batch_formatted="$(format_batch_for_log "$batch")"
  batch_ok=true
  preempt_file="$artifacts_dir/.batch-${batch_formatted}.preempt"
  record=""
  log_note=""
  if wait "$pid"; then
    batch_line="Test batch $batch SUCCEEDED"
  else
    batch_ok=false
  fi
  [ ! -f "$preempt_file" ] || record="$(cat "$preempt_file")"
  if [ "$batch_ok" = false ]; then
    failed_summary_log="$artifacts_dir/test-$batch_formatted-FAILED.log"
    case "$record" in
      *" outcome=no-time" | *" outcome=no-capacity" | *" outcome=delete-timeout" | *" outcome=retries-off" | *" outcome=watchdog")
        # Whatever log the killed batch left belongs to the preempted attempt.
        failed_summary_log="$artifacts_dir/test-$batch_formatted-PREEMPTED.log"
        if [ -f "$artifacts_dir/test-$batch_formatted.log" ]; then
          mv "$artifacts_dir/test-$batch_formatted.log" "$failed_summary_log" || true
        fi
        if [ -f "$artifacts_dir/configure-vm-$batch_formatted.log" ]; then
          mv "$artifacts_dir/configure-vm-$batch_formatted.log" \
            "$artifacts_dir/configure-vm-$batch_formatted-PREEMPTED.log" || true
        fi
        ;;
    esac
    if [ ! -f "$failed_summary_log" ] && [ -f "$artifacts_dir/test-$batch_formatted.log" ]; then
      # The batch failed without renaming its own log.  A batch the watchdog
      # kills never reaches that rename, because the kill takes out the process
      # group that would have done it.  Rename it here instead: the -FAILED
      # suffix is how analyze-test-failures discovers which batches to analyse,
      # so a log left under its running name gets no fv-tests-guru diagnosis and
      # no DIAGS artifact, and the failure reaches CI reporting as nothing but
      # the summary line below.  Safe at this point: we are past `wait`, so the
      # batch is finished and nothing is still writing to the log.
      mv "$artifacts_dir/test-$batch_formatted.log" "$failed_summary_log" ||
        failed_summary_log="$artifacts_dir/test-$batch_formatted.log"
      # Reaching here means the batch never ran its own failure handler, so the
      # log stops wherever the batch was killed.  Say so in the log itself: it
      # is now an input to fv-tests-guru, and a truncated transcript otherwise
      # reads as a test that simply stopped emitting.  Best-effort under the
      # script's `set -e`: a full disk is one of the things that gets a batch
      # killed in the first place, and losing the marker must not cost us the
      # summary, the failure exit code, or the watchdog cleanup below.
      printf '\n===== Batch %s did not complete: killed before it could finish, so this log is truncated mid-run =====\n' \
        "$batch" >> "$failed_summary_log" ||
        echo "  Could not mark $failed_summary_log as truncated (rc=$?)"
    fi
    batch_line="Test batch $batch FAILED; Log file will be uploaded as artifact $failed_summary_log"
    log_note="; Log file will be uploaded as artifact $failed_summary_log"
    final_result=1
  fi
  # Cancel this batch's watchdog now that it has finished, preventing
  # the PID-reuse race that a single global watchdog would have.
  wd_pid=${watchdog_pids[$i]}
  if [ -n "$wd_pid" ]; then
    kill "$wd_pid" 2>/dev/null || true
    wait "$wd_pid" 2>/dev/null || true
  fi

  outcome=completed
  [ "$batch_ok" = true ] || outcome=failed
  if [ -n "$record" ]; then
    # A retry the watchdog killed never recorded how it ended.
    if [[ "$record" == *" outcome=retried" ]]; then
      if [ "$batch_ok" = true ]; then record+="-pass"; else record+="-fail"; fi
    fi
    outcome="${record##* outcome=}"
    preempt_at="$(sed -n 's/.* at=\([^ ]*\) .*/\1/p' <<<"$record")"
    preempt_lines+=( "FV-PREEMPT $record" )
    case "$outcome" in
      retried-pass)
        summary+=( "Test batch $batch PREEMPTED at $preempt_at; retried on on-demand VM: SUCCEEDED" )
        preempt_retried_pass=$((preempt_retried_pass + 1)) ;;
      retried-fail)
        summary+=( "Test batch $batch PREEMPTED at $preempt_at; retried on on-demand VM: FAILED${log_note}" )
        preempt_retried_fail=$((preempt_retried_fail + 1)) ;;
      genuine-fail)
        summary+=( "Test batch $batch had already FAILED when its spot VM was preempted at $preempt_at; not retried${log_note}" )
        preempt_after_failure=$((preempt_after_failure + 1)) ;;
      passed-uncollected)
        summary+=( "Test batch $batch SUCCEEDED; its spot VM was preempted at $preempt_at before artifacts were collected, and there was no rerun" )
        preempt_not_retried=$((preempt_not_retried + 1)) ;;
      check-failed)
        summary+=( "Test batch $batch FAILED and could not check whether its spot VM was preempted; not retried${log_note}" )
        preempt_check_failed=$((preempt_check_failed + 1)) ;;
      *)
        summary+=( "Test batch $batch PREEMPTED at $preempt_at; not retried ($outcome)${log_note}" )
        preempt_not_retried=$((preempt_not_retried + 1)) ;;
    esac
  else
    summary+=( "$batch_line" )
  fi
  echo "$batch $vm_name_prefix$batch ${vm_zone[$vm_name_prefix$batch]} $outcome" >> "$batch_outcomes_file"
done

if [ "${VM_PROVISIONING_MODEL:-STANDARD}" = SPOT ]; then
  touch "$capacity_scores_file"
  # Joins this run's capacity scores with what happened to each batch, for
  # tuning when to trust spot.
  jq -n \
    --arg run "$(spot_run_id)" --arg lane "$(spot_lane_id)" \
    --arg queried_at "$(cat "${capacity_scores_file}.at" 2>/dev/null)" \
    --arg provisioning "$vm_provisioning_model" --arg type "$vm_machine_type" \
    --rawfile scores "$capacity_scores_file" --rawfile batches "$batch_outcomes_file" '
      def rows: split("\n") | map(select(length > 0) | split(" "));
      {run: $run, lane: $lane, queried_at: $queried_at,
       scores: ($scores | rows | map({type: .[0], zone: .[1],
         obtainability: (.[2] | tonumber? // .), estimated_uptime: .[3]})),
       created: {provisioning: $provisioning, type: $type},
       batches: ($batches | rows | map({batch: .[0], vm: .[1], zone: .[2], outcome: .[3]}))}' \
    > "$artifacts_dir/fv-capacity.json" ||
    echo "error: could not write fv-capacity.json; carrying on."
fi

echo
echo "===== Shutting down test monitors ====="
for pid in "${monitor_pids[@]}"; do
  # Note: negative PID to kill the entire process group.
  kill -TERM "-$pid" || true
done

echo "===== Results summary ====="
echo "  ${vm_create_summary}"
for s in "${summary[@]}"; do
  echo "  $s"
done
if [ ${#preempt_lines[@]} -gt 0 ]; then
  echo "  Preempted batches: $((preempt_retried_pass + preempt_retried_fail + preempt_not_retried))" \
    "(retried and passed: $preempt_retried_pass, retried and failed: $preempt_retried_fail, not retried: $preempt_not_retried);" \
    "failed batches whose preemption check failed: $preempt_check_failed;" \
    "failed batches preempted only after failing: $preempt_after_failure"
fi
echo
for l in "${preempt_lines[@]}"; do
  echo "$l"
done

if [ $final_result = 0 ] && [ -n "${BATCH_MEMO_PREFIX:-}" ] &&
  ! printf '%s\n' "${preempt_lines[@]}" | grep -q ' outcome=passed-uncollected$'; then
  batch_memo_record_lane "$artifacts_dir" "${all_batches[@]}"
fi
if [ -n "${BATCH_MEMO_LANE:-}" ]; then
  batch_memo_report "$artifacts_dir" "${#all_batches[@]}" "$final_result"
fi

echo "===== Done, exiting with RC=$final_result ====="

exit $final_result
