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

APP_DIR=/opt/pi-camera-bridge
CONFIG="$APP_DIR/config.json"

if [[ ! -f "$APP_DIR/.start-image-template" ]]; then
  echo "Kein neutrales IRL-StreamPilot-Startimage erkannt. Abbruch." >&2
  exit 2
fi

if [[ -f "$APP_DIR/config.example.json" ]]; then
  install -o picam -g picam -m 0600 "$APP_DIR/config.example.json" "$CONFIG"
fi

rm -rf "$APP_DIR/uploads"
install -d -o picam -g picam -m 0750 "$APP_DIR/uploads"
rm -f "$APP_DIR/.license-code" "$APP_DIR/.app-version"

rm -f /etc/machine-id
systemd-machine-id-setup
rm -f /var/lib/irl-streampilot/device-id
rm -f /etc/ssh/ssh_host_* 2>/dev/null || true
ssh-keygen -A >/dev/null 2>&1 || true

hostnamectl set-hostname irl-streampilot 2>/dev/null || hostname irl-streampilot
printf 'irl-streampilot\n' >/etc/hostname
if grep -qE '^127\.0\.1\.1[[:space:]]' /etc/hosts 2>/dev/null; then
  sed -i 's/^127\.0\.1\.1[[:space:]].*/127.0.1.1\tirl-streampilot/' /etc/hosts
else
  printf '127.0.1.1\tirl-streampilot\n' >>/etc/hosts
fi

# WLAN meldet den festen Namen an den Router. LAN bekommt bewusst einen
# getrennten technischen Namen: Zwei unterschiedliche Netzwerkadapter mit
# demselben DHCP-Namen lassen manche Router auf einer alten Adresse hängen.
if command -v nmcli >/dev/null 2>&1; then
  while IFS=: read -r profile type _device; do
    [[ -n "$profile" ]] || continue
    case "$type" in
      802-11-wireless)
        nmcli connection modify "$profile" ipv4.dhcp-hostname irl-streampilot ipv4.dhcp-send-hostname yes ipv6.method disabled >/dev/null 2>&1 || true
        ;;
      802-3-ethernet)
        nmcli connection modify "$profile" ipv4.dhcp-hostname irl-streampilot-wired ipv4.dhcp-send-hostname yes ipv6.method disabled >/dev/null 2>&1 || true
        ;;
    esac
  done < <(nmcli -t -f NAME,TYPE,DEVICE connection show 2>/dev/null || true)

  # Prefer wired networking, but keep Wi-Fi associated as a warm fallback.
  # Route metrics choose Ethernet whenever it is available.
  while IFS=: read -r profile type _device; do
    [[ -n "$profile" ]] || continue
    case "$type" in
      802-3-ethernet) nmcli connection modify "$profile" connection.autoconnect-priority 100 ipv4.route-metric 100 >/dev/null 2>&1 || true ;;
      802-11-wireless) nmcli connection modify "$profile" connection.autoconnect-priority 50 ipv4.route-metric 600 >/dev/null 2>&1 || true ;;
    esac
  done < <(nmcli -t -f NAME,TYPE,DEVICE connection show 2>/dev/null || true)
  nmcli device connect wlan0 >/dev/null 2>&1 || true
  nmcli connection reload >/dev/null 2>&1 || true
fi

rm -f "$APP_DIR/.start-image-template"
systemctl restart pi-camera-bridge
systemctl enable --now avahi-daemon >/dev/null 2>&1 || true
systemctl restart avahi-daemon >/dev/null 2>&1 || true
echo "IRL StreamPilot Startimage für den ersten Einsatz vorbereitet."
