#!/usr/bin/env bash
# St. Thomas Rev E capture seat: hostname topbox6 + rclone logs/6.
# Does NOT convert GA 1-5. Does NOT set POG422_UARTD_INJECT=1.
# Linux user stays topbox. No sudo reboot.
#
#   cd ~/EtherGold/sync
#   bash stamp_pos6_capture.sh

if grep -q $'\r' "${BASH_SOURCE[0]}" 2>/dev/null; then
  sed -i 's/\r$//' "${BASH_SOURCE[0]}"
  exec bash "${BASH_SOURCE[0]}" "$@"
fi

set -euo pipefail

SYNC="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# shellcheck source=ethergold_paths.sh
source "${SYNC}/ethergold_paths.sh"

NEW_HOST="topbox6"
POS=6
LABEL="topbox6"
BRIDGE_ENV="${ETHERGOLD_ROOT}/fixture-bridge.env"

_upsert() {
  local key="$1" val="$2" file="$3"
  if [[ ! -f "${file}" ]]; then
    printf '%s=%s\n' "${key}" "${val}" >"${file}"
    return 0
  fi
  if grep -q $'\r' "${file}" 2>/dev/null; then
    sed -i 's/\r$//' "${file}" 2>/dev/null || true
  fi
  if grep -qE "^${key}=" "${file}" 2>/dev/null; then
    sed -i "s|^${key}=.*|${key}=${val}|" "${file}"
  else
    printf '%s=%s\n' "${key}" "${val}" >>"${file}"
  fi
}

cur="$(hostname -s 2>/dev/null || hostname)"
if [[ "${cur}" != "${NEW_HOST}" ]]; then
  echo "hostname ${cur} → ${NEW_HOST}"
  sudo -n hostnamectl set-hostname "${NEW_HOST}"
  if [[ -f /etc/hosts ]]; then
    if grep -q '^127.0.1.1' /etc/hosts; then
      sudo -n sed -i "s/^127.0.1.1.*/127.0.1.1\t${NEW_HOST}/" /etc/hosts
    else
      echo -e "127.0.1.1\t${NEW_HOST}" | sudo -n tee -a /etc/hosts >/dev/null
    fi
  fi
else
  echo "hostname already ${NEW_HOST}"
fi

mkdir -p "$(dirname "${BRIDGE_ENV}")"
if [[ ! -f "${BRIDGE_ENV}" && -f "${SYNC}/fixture_bridge.env.example" ]]; then
  cp "${SYNC}/fixture_bridge.env.example" "${BRIDGE_ENV}"
fi
_upsert FIXTURE_POS "${POS}" "${BRIDGE_ENV}"
_upsert PI_LABEL "${LABEL}" "${BRIDGE_ENV}"
# Capture seat only — never turn uartd inject on.
if grep -qE '^POG422_UARTD_INJECT=' "${BRIDGE_ENV}" 2>/dev/null; then
  _upsert POG422_UARTD_INJECT 0 "${BRIDGE_ENV}"
fi
if [[ -f "${SYNC}/rclone.env" ]]; then
  _upsert FIXTURE_POS "${POS}" "${SYNC}/rclone.env"
fi

export FIXTURE_POS="${POS}"
bash "${SYNC}/install_sync.sh"

echo "stamp_pos6_capture: hostname=$(hostname -s 2>/dev/null || hostname) FIXTURE_POS=${POS}"
echo "  SSH user stays topbox. Do not convert GA 1-5. inject stays 0."
