#!/bin/bash
# ============================================================
# Repack the AI-Phone LOCK bundle vault with the current bt-ai-bridge:latest
# (the one live program since 2026-10-05; the old bt-ai-phone program was removed).
#   ~/AI-Phone-Lock-Deploy/vault.img  (lock template, key = keyserver master)
# (The key-in-folder "normal" bundle ~/AI-Phone-Deploy was retired 2026-09-28:
#  only locked bundles are shipped.)
# Only ai-phone-image.tar inside the vault is replaced; configs/.env/calls.db
# (the blank template) are left untouched. The old vault is backed up first.
# cryptsetup runs in a privileged throwaway container, nothing installed on host.
# ============================================================
set -e
STAMP=$(date +%Y%m%d-%H%M%S)
LOCK=~/AI-Phone-Lock-Deploy
MASTER=~/BT-KeyServer/vault-master.key
WORK=~/.ai-phone-repack-work            # NOT /tmp (3.6G tmpfs)
BK=~/bridge-backups/vaults-pre-repack-$STAMP
for f in "$LOCK/vault.img" "$MASTER"; do
  [ -f "$f" ] || { echo "missing: $f"; exit 1; }
done
SRC_IMAGE=bt-ai-bridge:latest
docker image inspect $SRC_IMAGE >/dev/null 2>&1 || { echo "image $SRC_IMAGE not built"; exit 1; }
# never start while a call is active (image export keeps 1-2 processor cores busy for a minute or two)
CALLS=$(docker exec BT-AI-Bridge asterisk -rx 'core show channels' 2>/dev/null | awk '/active channels/{print $1}')
[ "${CALLS:-0}" = "0" ] || { echo "active calls: $CALLS - try again when the line is free"; exit 1; }

echo "[1/4] backing up current vault -> $BK"
mkdir -p "$BK"
cp -a "$LOCK/vault.img"   "$BK/vault-lock.img"

echo "[2/4] exporting image (docker save | gzip) …"
rm -rf "$WORK"; mkdir -p "$WORK"
docker tag $SRC_IMAGE ai-phone-image:latest
docker save ai-phone-image:latest | nice -n 19 gzip -1 > "$WORK/ai-phone-image.tar"
ls -l "$WORK/ai-phone-image.tar"

swap() {  # $1 = vault dir, $2 = key file, $3 = label
  echo "[3/4] $3: replacing ai-phone-image.tar inside $1/vault.img …"
  docker run --rm --privileged \
    -v "$1":/v -v "$WORK":/new:ro -v "$2":/k:ro ubuntu:24.04 bash -c '
set -e
apt-get update -qq >/dev/null 2>&1 && apt-get install -y -qq cryptsetup-bin >/dev/null 2>&1
cryptsetup open --key-file /k /v/vault.img rp
mkdir -p /m && mount /dev/mapper/rp /m
echo "  before:"; ls -la /m
# the new image must fit BEFORE the old one is removed (free space + size of the old file)
NEED=$(stat -c %s /new/ai-phone-image.tar); OLDSZ=$(stat -c %s /m/ai-phone-image.tar 2>/dev/null || echo 0); FREE=$(df -B1 --output=avail /m | tail -1)
if [ $((FREE + OLDSZ - 20000000)) -lt "$NEED" ]; then echo "NEW IMAGE DOES NOT FIT ($NEED bytes needed) - vault left unchanged"; umount /m; cryptsetup close rp; exit 1; fi
rm -f /m/ai-phone-image.tar
cp /new/ai-phone-image.tar /m/ai-phone-image.tar
sync
echo "  after:"; ls -la /m; df -h /m | tail -1
[ -f /m/calls.db ] && [ -d /m/configs ] && [ -f /m/.env ] || { echo "TEMPLATE FILES MISSING"; exit 1; }
umount /m && cryptsetup close rp
cryptsetup open --test-passphrase --key-file /k /v/vault.img && echo "  VAULT-OK (key verified)"
chown 1001:1001 /v/vault.img
'
}
swap "$LOCK"   "$MASTER"           "lock"

echo "[4/4] cleaning up …"
rm -rf "$WORK"
ls -la --time-style=+%F_%T "$LOCK/vault.img"
echo "DONE $STAMP — backup in $BK"
