#!/bin/bash
# Usage: mirrordash-wifi-country SE
#   Sets the Wi-Fi country (applies at the next start). Run by pi through sudo, so the code is checked here.
#
# cmdline.txt is on the boot partition of the slot that boots, and a power cut while it is written must
# never leave it without root= (a kernel panic, and a mirror that restarts into the same slot for good).
# FAT has no journal: replacing the file (raspi-config's sed -i, or any new file moved over it) changes
# the folder and the allocation table in writes the card may persist in any order, and one order frees
# the file's cluster while the folder still points at it (fsck.fat then empties it; found by replaying
# every state a cut can leave, ARCHITECTURE #58). So the file is written over in place instead: the image
# ships cfg80211.ieee80211_regdom=00 and a country code is always two letters, so the line keeps its
# length and only its data sector changes. A cmdline.txt of another length (one without the setting) is
# replaced the old way: a new file, synced, moved over it, synced again.
set -euo pipefail
[[ "${1:-}" =~ ^[A-Z]{2}$ ]] || { echo "mirrordash-wifi-country: invalid country code" >&2; exit 2; }

# Fixed, never from the environment: pi runs this as root (tests/test_audit_image.py swaps the text)
CMDLINE=/boot/firmware/cmdline.txt

# One line: the old country (if any) out, the new one at the end. Made in RAM, not on the card.
new=$(mktemp)
trap 'rm -f "$new"' EXIT
sed -e 's/[[:space:]]*cfg80211\.ieee80211_regdom=[^[:space:]]*//g' -e "s/\$/ cfg80211.ieee80211_regdom=$1/" \
    "$CMDLINE" > "$new"
if ! grep -q 'root=' "$new"; then
  echo "mirrordash-wifi-country: $CMDLINE has no root=; left as it is" >&2
  exit 1
fi
if cmp -s "$new" "$CMDLINE"; then
  :  # already this country: nothing written
elif [ "$(stat -c %s "$new")" = "$(stat -c %s "$CMDLINE")" ]; then
  dd if="$new" of="$CMDLINE" conv=notrunc,fsync status=none
else
  cp "$new" "$CMDLINE.mirrordash-tmp"
  sync "$CMDLINE.mirrordash-tmp"
  mv "$CMDLINE.mirrordash-tmp" "$CMDLINE"
  sync "$CMDLINE"
fi

# Now as well, not only from the next start (what raspi-config did too)
iw reg set "$1" 2>/dev/null || true
