#!/bin/bash
#
# uplinkswap - promote an existing uplink to 'main' (quick main selection).
#
# Endian/OpenFW treats the uplink NAMED 'main' as the chain leader/default
# gateway owner everywhere (getActiveUplinkOfChain('main'), hooks, UI).
# The only consistent way to change the main is to swap the *configuration
# slots* of 'main' and the chosen uplink under /var/efw/uplinks:
#
#   1. stop both links (short outage, only these two)
#   2. swap the two directories
#   3. clear stale runtime state files of both slots
#   4. backup-profile references: swap 'main'/'$TARGET' slot names in every uplink
#   5. start both again -- the daemon rescans, hooks fire mainchanged/addrchanged
#      and setdefaultgw rebuilds the default route automatically.
#
# Installed by OpenFW improvement "quick main selection" (2026-10-19).
# usage: uplinkswap [--dry-run] <uplink-name>
#
export PATH=/sbin:/usr/sbin:/bin:/usr/bin
# UPLINKS_RUNDIR is for sandbox tests only; via sudo env_reset it is dropped,
# so in production the default /var/efw/uplinks always applies.
RUNDIR="${UPLINKS_RUNDIR:-/var/efw/uplinks}"
DRYRUN=0
if [ "$1" = "--dry-run" ]; then
    DRYRUN=1
    shift
fi
TARGET="$1"

log()  { logger -t 'uplink[uplinkswap]' -p daemon.info "$*"; }
fail() { logger -t 'uplink[uplinkswap]' -p daemon.err "ERROR: $*"; exit 1; }

[ -n "$TARGET" ] || fail "usage: uplinkswap [--dry-run] <uplink>"
echo "$TARGET" | grep -qE '^[A-Za-z0-9_-]+$' || fail "invalid uplink name '$TARGET'"
[ "$TARGET" = "main" ] && fail "'main' is already the main uplink"
[ -d "$RUNDIR/main" ] || fail "no main uplink directory"
[ -f "$RUNDIR/main/settings" ] || fail "main uplink has no settings file"
[ -d "$RUNDIR/$TARGET" ] || fail "uplink '$TARGET' does not exist"
[ -f "$RUNDIR/$TARGET/settings" ] || fail "uplink '$TARGET' has no settings file"
grep -q '^ENABLED=on$' "$RUNDIR/$TARGET/settings" 2>/dev/null || fail "uplink '$TARGET' is disabled"
[ -f "$RUNDIR/$TARGET/active" ] || fail "uplink '$TARGET' was never started (no active state); refusing to promote it"

# documentation only: uplinks that were fallbacks OF $TARGET now fallback to
# the connection the old main had (they keep pointing to the same slot name)
grep -l '^BACKUPPROFILE='"$TARGET"'$' "$RUNDIR/"*/settings 2>/dev/null |
    grep -v "uplinks/main/" | grep -v "uplinks/$TARGET/" |
while read f; do
    log "NOTE: $(basename "$(dirname "$f")") used BACKUPPROFILE=$TARGET; it now falls back to the connection the old main had"
done

if [ "$DRYRUN" = "1" ]; then
    log "dry-run: validations passed for '$TARGET'; no changes made"
    exit 0
fi

# role-based descriptions (what the user asked), applied on EVERY swap so
# the labels stay stable through forward/reverse switches:
#   - the 'main' slot gets description "Main Link"
#   - the vacated slot gets "Backup" (the old main is now the first fallback)
write_name() {
    local f="$1" n="$2" tmp
    if grep -q '^NAME=' "$f"; then
        tmp=$(mktemp)
        awk -v nn="$n" '{ if ($0 ~ /^NAME=/) print "NAME=" nn; else print }' "$f" > "$tmp"
        cat "$tmp" > "$f"; rm -f "$tmp"
    else
        printf 'NAME=%s\n' "$n" >> "$f"
    fi
}

# Freeze the uplinks daemon for the whole promotion window: it would auto-
# re-start the just-stopped links (autostart) with the OLD settings before
# the swap lands, and its jobs may rewrite settings mid-swap. With SIGSTOP
# nothing races; on SIGCONT it rescans once and hooks rebuild routes with
# the NEW consistent state. The EXIT trap guarantees the daemon unfreezes
# even if the script dies in between.
DAEMON_PID=""
cleanup() {
    if [ -n "$DAEMON_PID" ] && kill -0 "$DAEMON_PID" 2>/dev/null; then
        kill -CONT "$DAEMON_PID" 2>/dev/null
        log "resumed uplinks daemon (pid $DAEMON_PID)"
        DAEMON_PID=""
    fi
}
trap cleanup EXIT

log "Promoting uplink '$TARGET' to main: frozen daemon, stopping 'main' and '$TARGET'"
DPID=$(cat /var/run/uplinksdaemon.pid 2>/dev/null)
if [ -n "$DPID" ] && kill -0 "$DPID" 2>/dev/null; then
    DAEMON_PID="$DPID"
    kill -STOP "$DAEMON_PID"
    log "froze uplinks daemon (pid $DAEMON_PID) for the promotion window"
else
    log "uplinks daemon not found; proceeding without freeze"
fi

/etc/rc.d/uplinks stop main >/dev/null 2>&1
/etc/rc.d/uplinks stop "$TARGET" >/dev/null 2>&1
sleep 4

log "Swapping configuration slots of 'main' and '$TARGET'"
mv "$RUNDIR/main" "$RUNDIR/.uplinkswap.old" || fail "cannot move main directory"
if ! mv "$RUNDIR/$TARGET" "$RUNDIR/main"; then
    mv "$RUNDIR/.uplinkswap.old" "$RUNDIR/main"
    fail "swap failed mid-way, main restored"
fi
if ! mv "$RUNDIR/.uplinkswap.old" "$RUNDIR/$TARGET"; then
    fail "FATAL: old main is stranded in $RUNDIR/.uplinkswap.old - manual recovery needed"
fi

for d in "$RUNDIR/main" "$RUNDIR/$TARGET"; do
    rm -f "$d"/active "$d"/connecting "$d"/disconnecting "$d"/failure \
          "$d"/DEAD "$d"/notified "$d"/defaultgateway "$d"/data "$d"/pid.pid
done

# role-based descriptions: the 'main' slot becomes "Main Link" and the
# vacated slot becomes "Backup" (stable on every forward/reverse switch)
write_name "$RUNDIR/main/settings" "Main Link"
write_name "$RUNDIR/$TARGET/settings" "Backup"

# backup-profile references are stored as slot names ('main', 'uplinkN', ...).
# Swapping the 'main' and '$TARGET' slots means every BACKUPPROFILE value that
# pointed at one of those slots must be swapped too, otherwise the configured
# backup (failover) relationship is lost (e.g. 'main' would lose its backup).
# This is applied to ALL uplinks, not just the two being swapped.
for __f in "$RUNDIR"/*/settings; do
    [ -f "$__f" ] || continue
    if grep -q '^BACKUPPROFILE=' "$__f"; then
        __cur=$(sed -n 's/^BACKUPPROFILE=//p' "$__f" | head -n1)
        __new="$__cur"
        [ "$__cur" = "main" ] && __new="$TARGET"
        [ "$__cur" = "$TARGET" ] && __new="main"
        __tmp=$(mktemp)
        awk -v nn="$__new" '{ if ($0 ~ /^BACKUPPROFILE=/) print "BACKUPPROFILE=" nn; else print }' "$__f" > "$__tmp"
        cat "$__tmp" > "$__f"
        rm -f "$__tmp"
    fi
done
unset __f __cur __new __tmp

# start the new main FIRST and wait for it to come up (DHCP may need a few
# seconds for the lease) so links are settled before the daemon resumes
log "Starting new 'main' and '$TARGET' (old main as fallback)"
/etc/rc.d/uplinks start main >/dev/null 2>&1 || log "WARNING: start 'main' returned an error"
for i in 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20; do
    [ -f "$RUNDIR/main/active" ] && break
    sleep 1
done
sleep 2

# resume the daemon with the settled state and force a rescan: pending
# notifications wake it, it rescans the swapped settings and triggers the
# hooks, which rebuild the default route for the NEW main
cleanup
[ -n "$DPID" ] && kill -USR1 "$DPID" 2>/dev/null
sleep 2

/etc/rc.d/uplinks start "$TARGET" >/dev/null 2>&1 || log "WARNING: start '$TARGET' returned an error"

log "Promotion of '$TARGET' to main finished; daemon hooks will rebuild routes/services"
exit 0
