#!/usr/bin/env bash
# Start an X3 flashing shell on a native Ubuntu host. Never flashes a device.
set -Eeuo pipefail

die() { printf 'X3 flash: %s\n' "$*" >&2; exit 1; }

container_session() {
  cd /Linux_for_Tegra
  local name target filesystem export_file shell_pid="" status=0
  for name in tmp images; do
    target="$PWD/tools/kernel_flash/$name"
    filesystem=$(findmnt -n -o FSTYPE --target "$target")
    if ! mountpoint -q "$target" || [[ $filesystem != ext4 ]]; then
      die "$target must use temporary ext4 storage; update the image before continuing."
    fi
  done

  # This launcher supplies exports even with the first temporary-storage image.
  mkdir -p /etc/exports.d /run/nvidia_initrd_flash /run/sendsigs.omit.d
  export_file=$(mktemp --suffix=.exports /etc/exports.d/x3-launcher.XXXXXX)
  # shellcheck disable=SC2317 # Called by the EXIT trap.
  cleanup_container() {
    local result=$?
    trap - EXIT
    trap '' HUP INT TERM
    service nfs-kernel-server stop || result=1
    # nfsd kernel threads may be outside the container's PID namespace.
    rpc.nfsd 0 || result=1
    service rpcbind stop || result=1
    rm -f -- "$export_file"
    exit "$result"
  }
  # shellcheck disable=SC2317 # Called by HUP/INT/TERM traps.
  forward_container_signal() {
    local signal=$1
    if [[ -n $shell_pid ]]; then
      # An interactive Bash ignores TERM; HUP closes it and its terminal jobs.
      [[ $signal != TERM ]] || signal=HUP
      kill -s "$signal" "$shell_pid" 2>/dev/null || true
    else
      case "$signal" in HUP) exit 129 ;; INT) exit 130 ;; TERM) exit 143 ;; esac
    fi
  }
  trap cleanup_container EXIT
  trap 'forward_container_signal HUP' HUP
  trap 'forward_container_signal INT' INT
  trap 'forward_container_signal TERM' TERM

  local options=rw,nohide,insecure,no_subtree_check,async,no_root_squash client
  chmod 0755 tools/kernel_flash/images
  chown 0:0 tools/kernel_flash/images
  for client in 127.0.0.1 "${X3_FLASH_NFS_CLIENT:-fc00:1:1::/48}"; do
    printf '%s %s(%s)\n' "$PWD/tools/kernel_flash/images" "$client" "$options"
  done > "$export_file"
  touch /run/nvidia_initrd_flash/docker_host_network

  # Exercise NVIDIA's actual prerequisite and export checks before generation.
  # shellcheck disable=SC1091
  source tools/kernel_flash/l4t_network_flash.func
  # shellcheck disable=SC2034 # Read by NVIDIA's sourced functions.
  PERMISSION_STR=$options
  network_prerequisite usb0 "$PWD"
  network_export usb0 "$PWD" ""
  printf '\nX3 flash: temporary ext4 and NVIDIA NFS checks passed. Entering Bash.\n'
  bash -i <&0 &
  shell_pid=$!
  while true; do
    wait "$shell_pid" && status=0 || status=$?
    kill -0 "$shell_pid" 2>/dev/null || break
  done
  exit "$status"
}

if [[ ${1:-} == --container ]]; then
  container_session
fi
if [[ ${1:-} == --help ]]; then
  printf '%s\n' 'Usage: sudo bash start-x3-flash.sh' \
    'Optional environment: X3_FLASH_IMAGE, X3_FLASH_WORKSPACE, X3_FLASH_STORAGE_SIZE, X3_FLASH_NFS_CLIENT.' \
    'Temporarily stops host NFS/RPC services, verifies container NFS, then opens Bash.' \
    'Restores previously active host services on exit. Does not execute flashing.'
  exit
fi
(( $# == 0 )) || die 'Unexpected argument. Use --help for usage.'
(( EUID == 0 )) || die 'Run on the Ubuntu flashing host with: sudo bash start-x3-flash.sh'
[[ $(uname -s) == Linux && $(uname -m) == x86_64 ]] || die 'A native x86_64 Linux host is required.'
for tool in docker systemctl flock ss pgrep readlink; do
  command -v "$tool" >/dev/null || die "Missing host dependency: $tool"
done
[[ -d /run/systemd/system ]] || die 'The flashing host must run systemd.'

image=${X3_FLASH_IMAGE:-catdogai/lzc-x3:jetpack-7.2.1}
workspace=${X3_FLASH_WORKSPACE:-$PWD/workspace}
script_path=$(readlink -f -- "${BASH_SOURCE[0]}")
# Never stop local services while using a remote Docker daemon.
if [[ -n ${DOCKER_CONTEXT:-} ]]; then
  endpoint=$(docker context inspect "$DOCKER_CONTEXT" --format '{{.Endpoints.docker.Host}}')
elif [[ -n ${DOCKER_HOST:-} ]]; then
  endpoint=$DOCKER_HOST
else
  endpoint=$(docker context inspect --format '{{.Endpoints.docker.Host}}')
fi
[[ $endpoint == unix://* ]] || die 'Use the local Docker daemon on the flashing host.'
docker image inspect "$image" >/dev/null || die "Import or pull the flashing image first: $image"
mkdir -p -- "$workspace"
workspace=$(readlink -f -- "$workspace")
[[ $workspace != *','* && $script_path != *','* ]] || die 'Script and workspace paths must not contain commas.'

exec 9>/run/lock/lc-x3-flash.lock
flock -n 9 || die 'Another X3 flashing session is running on this host.'
# Refuse to interrupt an existing share or another container's RPC service.
[[ ! -s /var/lib/nfs/etab ]] || die 'This compatibility launcher requires a host without NFS shares. To reuse existing shares, use a rebuilt host-nfs-v2 image with the documented docker run command.'
host_pid_namespace=$(readlink /proc/1/ns/pid)
while read -r rpc_pid; do
  [[ -n $rpc_pid ]] || continue
  rpc_pid_namespace=$(readlink "/proc/$rpc_pid/ns/pid" 2>/dev/null) || continue
  [[ $rpc_pid_namespace == "$host_pid_namespace" ]] ||
    die 'Another container runs rpcbind/mountd. Exit that container before starting X3 flashing.'
done < <(pgrep -x 'rpcbind|rpc.mountd' || true)

units=()
restore_units=()
for unit in nfs-server.service nfs-mountd.service rpcbind.socket rpcbind.service; do
  load_state=$(systemctl show "$unit" --property=LoadState --value)
  [[ $load_state == loaded ]] || continue
  units+=("$unit")
  state=$(systemctl show "$unit" --property=ActiveState --value)
  case "$state" in
    active) restore_units+=("$unit") ;;
    inactive|failed) ;;
    *) die "Host service $unit is $state. Wait for it to settle and retry." ;;
  esac
done

session_id=$(cat /proc/sys/kernel/random/uuid)
container_name="lc-x3-flash-$session_id"
docker_pid=
# shellcheck disable=SC2317 # Called by the EXIT trap.
cleanup_host() {
  local result=$? owner container_state
  trap - EXIT
  trap '' HUP INT TERM
  # Only stop the container created by this invocation, including signal exits.
  if owner=$(docker inspect --format '{{index .Config.Labels "cloud.lazycat.x3-flash-session"}}' "$container_name" 2>/dev/null); then
    if [[ $owner == "$session_id" ]]; then
      docker stop --time 30 "$container_name" >/dev/null || result=1
      # Do not restore host RPC while the container might still be running.
      container_state=$(docker inspect --format '{{.State.Running}}' "$container_name" 2>/dev/null) || container_state=false
      if ! docker info >/dev/null 2>&1; then
        printf 'X3 flash: Docker is unavailable; host services remain stopped: %s\n' "${restore_units[*]}" >&2
        exit 1
      fi
      if [[ $container_state == true ]]; then
        printf 'X3 flash: container still running; host services remain stopped: %s\n' "${restore_units[*]}" >&2
        exit 1
      fi
      docker rm "$container_name" >/dev/null 2>&1 || true
    fi
  elif ! docker info >/dev/null 2>&1; then
    printf 'X3 flash: Docker is unavailable. Check the container before restoring host services: %s\n' "${restore_units[*]}" >&2
    exit 1
  fi
  if [[ -n $docker_pid ]]; then wait "$docker_pid" 2>/dev/null || true; fi
  if (( ${#restore_units[@]} )); then
    printf 'X3 flash: restoring host services: %s\n' "${restore_units[*]}"
    systemctl start "${restore_units[@]}" || result=1
  fi
  exit "$result"
}
trap cleanup_host EXIT
trap 'exit 129' HUP
trap 'exit 130' INT
trap 'exit 143' TERM

# The image entrypoint owns temporary ext4. This script owns export setup so
# both the original temporary-storage image and newer images behave alike.
# Create before stopping services so cleanup can always identify the container.
docker create -it --rm --privileged --network host \
  --name "$container_name" \
  --label "cloud.lazycat.x3-flash-session=$session_id" \
  --workdir /Linux_for_Tegra \
  -e X3_FLASH_HOST_NETWORK=0 \
  -e "X3_FLASH_STORAGE_SIZE=${X3_FLASH_STORAGE_SIZE:-96G}" \
  -e "X3_FLASH_NFS_CLIENT=${X3_FLASH_NFS_CLIENT:-fc00:1:1::/48}" \
  --mount type=bind,src=/dev/bus/usb,dst=/dev/bus/usb \
  --mount type=bind,src=/dev,dst=/dev \
  --mount "type=bind,src=$workspace,dst=/workspace" \
  --mount "type=bind,src=$script_path,dst=/opt/start-x3-flash.sh,readonly" \
  "$image" bash /opt/start-x3-flash.sh --container >/dev/null

if (( ${#units[@]} )); then
  printf 'X3 flash: temporarily stopping host NFS/RPC services.\n'
  if (( ${#restore_units[@]} )); then
    printf 'X3 flash: host services to restore after this container stops: %s\n' "${restore_units[*]}"
  fi
  systemctl stop "${units[@]}"
fi
listeners=$(ss -H -ltnu '( sport = :111 or sport = :2049 )')
[[ -z $listeners ]] || die "Ports 111/2049 are still occupied. Stop the conflicting service first:
$listeners"

docker start -ai "$container_name" <&0 9>&- &
docker_pid=$!
status=0
wait "$docker_pid" || status=$?
exit "$status"
