#!/bin/bash
# firstboot — first-boot init: resize rootfs, then discover hostname via PTR.
# Runs as a systemd oneshot service; sentinel /var/lib/firstboot.done marks
# success. Sentinel is written ONLY after PTR-driven hostname discovery
# succeeds — a failed lookup leaves the unit eligible to retry on next boot
# (e.g. once WireGuard / DNS settle).

set -euo pipefail

[[ -f /var/lib/firstboot.done ]] && exit 0

echo "firstboot: resizing root partition to fill disk"
ROOT_SOURCE=$(findmnt -no SOURCE /)
ROOT_DISK_NAME=$(lsblk -no PKNAME "$ROOT_SOURCE" 2>/dev/null)
if [[ -z "$ROOT_DISK_NAME" ]]; then
    echo "firstboot: cannot determine root disk from $ROOT_SOURCE, skipping resize" >&2
else
    ROOT_DISK="/dev/$ROOT_DISK_NAME"
    # Derive partition number: strip the disk prefix from the source device.
    # /dev/vda1  -> 1, /dev/sda1 -> 1, /dev/nvme0n1p1 -> 1
    ROOT_PART_NUM="${ROOT_SOURCE##"$ROOT_DISK"}"   # strip disk prefix (e.g. "p1" or "1")
    ROOT_PART_NUM="${ROOT_PART_NUM#p}"              # strip leading "p" for NVMe
    echo -e ',+' | sfdisk -N "$ROOT_PART_NUM" "$ROOT_DISK" --no-reread
    partprobe "$ROOT_DISK" || true
fi
btrfs filesystem resize max /

# Nibble-reverse an IPv6 address for ip6.routedvpn.com PTR lookup.
# Input: "2001:db8::1"  Output: "1.0.0.0...1.0.b.d.1.0.0.2"
ipv6_nibble_reverse() {
  local addr="$1"
  printf '%s\n' "$addr" | awk '
  {
    addr = $0
    # Expand :: shorthand.
    if (index(addr, "::") > 0) {
      split(addr, halves, "::")
      left  = halves[1]; right = halves[2]
      n_left  = (left  == "") ? 0 : split(left,  lp, ":")
      n_right = (right == "") ? 0 : split(right, rp, ":")
      missing = 8 - n_left - n_right
      full = ""
      for (i = 1; i <= n_left;   i++) full = full (full ? ":" : "") lp[i]
      for (i = 1; i <= missing;  i++) full = full (full ? ":" : "") "0"
      for (i = 1; i <= n_right;  i++) full = full (full ? ":" : "") rp[i]
      addr = full
    }
    # Zero-pad each 16-bit group, collect nibbles in reverse.
    n = split(addr, groups, ":")
    nibbles = ""
    for (i = n; i >= 1; i--) {
      padded = sprintf("%04s", groups[i])
      gsub(/ /, "0", padded)
      for (j = 4; j >= 1; j--) {
        nibbles = nibbles (nibbles != "" ? "." : "") substr(padded, j, 1)
      }
    }
    print nibbles
  }'
}

# Try to discover hostname from DNS PTR records in ip[6].routedvpn.com.
# sysprov publishes these via the ptrreg HTTP API at provisioning time,
# keyed by public IP. The rootfs looks them up here at first boot.
discover_hostname_from_dns() {
  local fqdn=""

  # Prefer IPv6 (more specific; systems may be v6-only).
  for ADDR in $(ip -br -6 ad sh | grep -vE '^lo|^wg' | awk '{print $3}' | cut -d/ -f1 | grep -v '^fe80'); do
    local nibbles
    nibbles=$(ipv6_nibble_reverse "$ADDR") || continue
    [[ -n "$nibbles" ]] || continue
    fqdn=$(dig +short +time=5 +tries=2 PTR "${nibbles}.ip6.routedvpn.com" 2>/dev/null | head -1 | sed 's/\.$//')
    [[ -n "$fqdn" ]] && break
  done

  # Fall back to IPv4.
  if [[ -z "$fqdn" ]]; then
    for ADDR in $(ip -br -4 ad sh | grep -vE '^lo|^wg' | awk '{print $3}' | cut -d/ -f1); do
      local rev
      rev=$(printf '%s\n' "$ADDR" | awk -F. '{print $4"."$3"."$2"."$1}')
      fqdn=$(dig +short +time=5 +tries=2 PTR "${rev}.ip.routedvpn.com" 2>/dev/null | head -1 | sed 's/\.$//')
      [[ -n "$fqdn" ]] && break
    done
  fi

  printf '%s' "$fqdn"
}

DISCOVERED=$(discover_hostname_from_dns || true)

if [[ -z "$DISCOVERED" ]]; then
  echo "firstboot: PTR lookup found no hostname; leaving 'unconfigured' and exiting WITHOUT sentinel so next boot can retry."
  exit 0
fi

echo "firstboot: discovered hostname from DNS: ${DISCOVERED}"
read -r -a FQDN <<< "$DISCOVERED"

echo "firstboot: setting mailname to ${FQDN[0]}"
echo "${FQDN[0]}" > /etc/mailname

# Short hostname: second word if given, otherwise first label of FQDN.
HOSTNAME="${FQDN[1]:-${FQDN[0]%%.*}}"
echo "firstboot: setting hostname to ${HOSTNAME}"
hostnamectl set-hostname "$HOSTNAME"

for ADDR in $(ip -br -4 ad sh | grep -vE '^lo|^wg' | awk '{print $3}' | cut -d/ -f1); do
    echo "${ADDR} ${FQDN[0]} ${HOSTNAME}" >> /etc/hosts
done

for ADDR in $(ip -br -6 ad sh | grep -vE '^lo|^wg' | awk '{print $3}' | cut -d/ -f1 | grep -v '^fe80'); do
    echo "${ADDR} ${FQDN[0]} ${HOSTNAME}" >> /etc/hosts
done

touch /var/lib/firstboot.done
echo "firstboot: done"
