#!/usr/bin/env bash
set -euo pipefail

log() {
  echo
  echo "==> $*"
}

warn() {
  echo "warning: $*" >&2
}

die() {
  echo "error: $*" >&2
  exit 1
}

have_command() {
  command -v "$1" >/dev/null 2>&1
}

require_root() {
  if [[ "${EUID:-$(id -u)}" -ne 0 ]]; then
    die "step 00 must be run as root"
  fi
}

prompt_reboot() {
  echo
  echo "Step 00 complete. Reboot before running step 01:"
  echo "  sudo reboot"

  if [[ -r /dev/tty ]]; then
    local answer=""
    printf "Reboot now? [y/N] " > /dev/tty
    read -r answer < /dev/tty || true
    case "$answer" in
      y|Y|yes|YES)
        reboot
        ;;
    esac
  fi
}

require_root

WIFI_COUNTRY="${WIFI_COUNTRY:-AU}"
BOOT_CONFIG_CHANGED=0
SOFTWARE_CHANGED=0
NETBIRD_CHANGED=0

log "Installing required software"
if ! have_command apt-get || ! have_command dpkg-query; then
  die "apt-get and dpkg-query are required on this image"
fi

packages=(
  curl
  jq
  openssl
  usbutils
  modemmanager
  libmbim-utils
  libqmi-utils
  network-manager
)

missing=()
for pkg in "${packages[@]}"; do
  if dpkg-query -W -f='${Status}' "$pkg" 2>/dev/null | grep -qx "install ok installed"; then
    echo "Already installed: $pkg"
  else
    missing+=("$pkg")
  fi
done

if [[ "${#missing[@]}" -gt 0 ]]; then
  echo "Installing: ${missing[*]}"
  apt-get update
  DEBIAN_FRONTEND=noninteractive apt-get install -y "${missing[@]}"
  SOFTWARE_CHANGED=1
else
  echo "All required packages are installed"
fi

log "Checking NetBird"
if have_command netbird; then
  echo "NetBird already installed: $(command -v netbird)"
else
  echo "Installing NetBird"
  curl -fsSL https://pkgs.netbird.io/install.sh | sh
  NETBIRD_CHANGED=1
  SOFTWARE_CHANGED=1
fi

log "Checking Raspberry Pi boot config"
if [[ -f /boot/firmware/config.txt ]]; then
  config_file="/boot/firmware/config.txt"
elif [[ -f /boot/config.txt ]]; then
  config_file="/boot/config.txt"
else
  die "could not find /boot/firmware/config.txt or /boot/config.txt"
fi

echo "Using config file: $config_file"
backup=""

ensure_config_backup() {
  if [[ -z "$backup" ]]; then
    backup="$config_file.bak.$(date +%Y%m%d-%H%M%S)"
    cp "$config_file" "$backup"
    echo "Backup created: $backup"
  fi
}

ensure_line() {
  local line="$1"

  if grep -qxF "$line" "$config_file"; then
    echo "Already set: $line"
  else
    echo "Adding: $line"
    ensure_config_backup
    echo "$line" >> "$config_file"
    BOOT_CONFIG_CHANGED=1
  fi
}

comment_line() {
  local line="$1"

  if grep -qxF "$line" "$config_file"; then
    echo "Commenting: $line"
    ensure_config_backup
    sed -i "s|^$line$|#$line|" "$config_file"
    BOOT_CONFIG_CHANGED=1
  elif grep -qxF "#$line" "$config_file"; then
    echo "Already commented: $line"
  else
    echo "Not present, nothing to comment: $line"
  fi
}

uncomment_or_add_line() {
  local line="$1"

  if grep -qxF "$line" "$config_file"; then
    echo "Already enabled: $line"
  elif grep -qxF "#$line" "$config_file"; then
    echo "Uncommenting: $line"
    ensure_config_backup
    sed -i "s|^#$line$|$line|" "$config_file"
    BOOT_CONFIG_CHANGED=1
  else
    echo "Adding: $line"
    ensure_config_backup
    echo "$line" >> "$config_file"
    BOOT_CONFIG_CHANGED=1
  fi
}

log "Updating boot config"
comment_line "otg_mode=1"
ensure_line "dtoverlay=dwc2,dr_mode=host"
uncomment_or_add_line "dtparam=i2c_arm=on"
ensure_line "dtparam=i2c_vc=on"
ensure_line "dtoverlay=i2c-rtc,pcf85063a,i2c_csi_dsi"
ensure_line "dtparam=ant2"
ensure_line "gpio=6=op,dh"

echo "Relevant config lines:"
grep -nE 'otg_mode|dwc2|i2c_arm|i2c_vc|i2c-rtc|ant2|gpio=6' "$config_file" || true

log "Checking Wi-Fi country"
if have_command raspi-config; then
  current_country=""
  if current_country="$(raspi-config nonint get_wifi_country 2>/dev/null)"; then
    if [[ "$current_country" == "$WIFI_COUNTRY" ]]; then
      echo "Wi-Fi country already set to $WIFI_COUNTRY"
    else
      echo "Setting Wi-Fi country to $WIFI_COUNTRY"
      raspi-config nonint do_wifi_country "$WIFI_COUNTRY"
      BOOT_CONFIG_CHANGED=1
    fi
  else
    warn "could not read current Wi-Fi country; attempting to set it"
    raspi-config nonint do_wifi_country "$WIFI_COUNTRY"
    BOOT_CONFIG_CHANGED=1
  fi
else
  warn "raspi-config not found; skipping Wi-Fi country setup"
fi

log "Step 00 summary"
if [[ "$SOFTWARE_CHANGED" -eq 1 ]]; then
  echo "Software packages were installed or updated."
else
  echo "No software package changes were needed."
fi

if [[ "$NETBIRD_CHANGED" -eq 1 ]]; then
  echo "NetBird was installed."
else
  echo "NetBird was already installed."
fi

if [[ "$BOOT_CONFIG_CHANGED" -eq 1 ]]; then
  echo "Boot or Wi-Fi configuration changed."
  if [[ -n "$backup" ]]; then
    echo "Backup saved at: $backup"
  fi
else
  echo "No boot or Wi-Fi configuration changes were needed."
fi

prompt_reboot
