#!/bin/sh
# OMEGA Maestro — update from / backup to a USB stick.
#
# UPDATE: insert a stick that carries a folder called  omega-update  with
# exactly one omega-hub-*.tar.gz and its .sha256 next to it. The box verifies
# the checksum, pre-reads the whole archive, installs, syncs, restarts the
# bridge, and writes update-result.txt back onto the stick so the person can
# read what happened on any computer.
#
# BACKUP: insert a stick that carries a folder called  omega-backup  and the
# box writes its complete settings into a timestamped subfolder — pull the
# stick, done. Restoring goes through Tools > Backup & restore.
#
# The folder names are the consent markers: a stick without either folder does
# nothing — settings must never leak onto a random stick someone plugs in.
# Same-version reinstall is allowed on purpose — this doubles as the no-laptop
# rescue path.

[ "$ACTION" = "add" ] || exit 0
case "$DEVNAME" in
  sd[a-z][0-9]*) ;;
  sd[a-z]) ;;               # sticks without a partition table
  *) exit 0 ;;
esac

LOCK=/tmp/omega-usb.lock
[ -f "$LOCK" ] && exit 0
touch "$LOCK"
trap 'rm -f "$LOCK"' EXIT

MNT=/tmp/omega-usb
LOG="logger -t omega-usb"
mkdir -p "$MNT"

mounted=0
for t in vfat exfat ntfs auto; do
  if mount -t "$t" "/dev/$DEVNAME" "$MNT" 2>/dev/null; then mounted=1; break; fi
done
[ "$mounted" = 1 ] || { $LOG "could not mount /dev/$DEVNAME"; exit 0; }

# ── backup path: omega-backup/ on the stick = "please copy your settings here"
BDIR="$MNT/omega-backup"
if [ -d "$BDIR" ]; then
  STAMP=$(date '+%Y%m%d-%H%M%S')
  DEST="$BDIR/$STAMP"
  mkdir -p "$DEST"
  n=0
  for f in omega-config.json omega-names.json omega-manual.json omega-zones.json omega-scenes.json omega-actionlog.json; do
    [ -f "/etc/omega-data/$f" ] && cp "/etc/omega-data/$f" "$DEST/" && n=$((n+1))
  done
  {
    echo "OMEGA Maestro instellingen-backup"
    echo "gemaakt: $(date '+%Y-%m-%d %H:%M:%S')"
    echo "versie:  $(grep -o '"version": *"[^"]*"' /usr/lib/omega-bridge/bridge/package.json 2>/dev/null | grep -o '[0-9.]*')"
    echo "bestanden: $n"
    echo "terugzetten: bedienpagina > Tools > Backup & restore"
  } > "$DEST/LEES-MIJ.txt"
  sync
  $LOG "settings backup written to stick ($n files, $STAMP)"
fi

DIR="$MNT/omega-update"
if [ ! -d "$DIR" ]; then
  umount "$MNT" 2>/dev/null
  exit 0                                   # no update folder — we're done
fi

RESULT="$DIR/update-result.txt"
say() { echo "$(date '+%Y-%m-%d %H:%M:%S')  $1" >> "$RESULT"; $LOG "$1"; }
: > "$RESULT"
say "OMEGA Maestro USB update gestart"

PKG=$(ls "$DIR"/omega-hub-*.tar.gz 2>/dev/null | head -1)
if [ -z "$PKG" ]; then
  say "FOUT: geen omega-hub-*.tar.gz in omega-update/"
  sync; umount "$MNT"; exit 0
fi
BASE=$(basename "$PKG")
say "pakket gevonden: $BASE"

if [ ! -f "$PKG.sha256" ]; then
  say "FOUT: $BASE.sha256 ontbreekt — zonder controle installeren we niet"
  sync; umount "$MNT"; exit 0
fi

cd "$DIR"
if ! sha256sum -c "$BASE.sha256" >/dev/null 2>&1; then
  say "FOUT: checksum klopt niet — bestand beschadigd of verkeerd. Niets geinstalleerd."
  sync; umount "$MNT"; exit 0
fi
say "checksum klopt"

if ! tar -tzf "$PKG" > /dev/null 2>&1; then
  say "FOUT: archief onleesbaar. Niets geinstalleerd."
  sync; umount "$MNT"; exit 0
fi
say "archief compleet leesbaar"

OLD=$(grep -o '"version": *"[^"]*"' /usr/lib/omega-bridge/bridge/package.json 2>/dev/null | grep -o '[0-9.]*')
if tar -xzf "$PKG" -C / 2>>"$RESULT"; then
  sync
  NEW=$(grep -o '"version": *"[^"]*"' /usr/lib/omega-bridge/bridge/package.json 2>/dev/null | grep -o '[0-9.]*')
  say "GELUKT: geinstalleerd ${OLD:-?} -> ${NEW:-?}"
  say "de bedienpagina herstart nu — geef hem een minuut"
  say "stick kan eruit"
else
  say "FOUT: uitpakken mislukte — zie regels hierboven"
fi
sync
umount "$MNT" 2>/dev/null

/etc/init.d/omega-bridge enable 2>/dev/null
/etc/init.d/omega-bridge restart 2>/dev/null
sync
exit 0
