#!/usr/bin/env bash
# Set prod chain-hop identity from WLAN IP last octet: topbox<octet>
#
# Usage (on Pi):
#   sudo bash set_chain_hostname.sh 192
#   sudo OCTET=250 bash set_chain_hostname.sh
#
# Restarts ethergold.service so bridge --pi-label picks up the new hostname.

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

OCTET="${1:-${OCTET:-}}"
if [[ -z "${OCTET}" ]] || ! [[ "${OCTET}" =~ ^[0-9]{1,3}$ ]]; then
  echo "FATAL: provide IP last octet 0-255 (arg or OCTET=)" >&2
  exit 1
fi

if [[ "${EUID}" -ne 0 ]]; then
  echo "FATAL: run with sudo" >&2
  exit 1
fi

NEW_HOST="topbox${OCTET}"
OLD_HOST="$(hostname -s 2>/dev/null || hostname)"

if [[ "${OLD_HOST}" == "${NEW_HOST}" ]]; then
  echo "hostname already ${NEW_HOST}"
else
  echo "=== set hostname ${OLD_HOST} -> ${NEW_HOST} ==="
  hostnamectl set-hostname "${NEW_HOST}"
  if [[ -f /etc/hosts ]]; then
    if grep -q '^127.0.1.1' /etc/hosts; then
      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}" >> /etc/hosts
    fi
  fi
fi

if systemctl is-active ethergold >/dev/null 2>&1; then
  echo "--- restart ethergold (refresh --pi-label) ---"
  systemctl restart ethergold
  sleep 2
  systemctl is-active ethergold
elif systemctl is-active fixture-prod >/dev/null 2>&1; then
  echo "--- restart fixture-prod (legacy) ---"
  systemctl restart fixture-prod
  sleep 2
  systemctl is-active fixture-prod
fi

echo "=== done host=$(hostname -s) pi_label should match in bridge args ==="
