#!/usr/bin/env bash
# Download, verify and unpack one bundle. Resumable: rerun after an interruption.
#   ./download.sh final12        (also: final13, final11)
# Env: PROXY_ARG  e.g. export PROXY_ARG="-x http://172.16.13.110:3128"
#      B          parent dir for bundles (default /data)
set -euo pipefail
NAME="${1:?usage: download.sh final12|final13|final11}"
B="${B:-/data}"; SRV="${SRV:-http://23.88.61.31}"   # dist.gcp.emteria.com; IP because the node's resolver does not know the name; F="bundle-vodafone-idnow-${NAME}.tar.zst"
step() { printf '\n==> %s  [%s]\n' "$*" "$(date -u +%H:%M:%S)"; }
cd "$B"
step "downloading $F.sha256"
curl -fsS ${PROXY_ARG:-} -O "$SRV/$F.sha256"
step "downloading $F (5.7 GiB, resumes with -C - if interrupted)"
curl -fS ${PROXY_ARG:-} -C - -O "$SRV/$F" || { echo "curl failed; rerun this script to resume"; exit 1; }
step "verifying checksum"
sha256sum -c "$F.sha256"
step "unpacking into $B/vodafone-idnow-$NAME"
[ -d "vodafone-idnow-$NAME" ] && echo "   already unpacked, skipping" || zstd -d < "$F" | tar -x -C "$B"
step "verifying bundle files"
( cd "vodafone-idnow-$NAME" && sha256sum --quiet -c SHA256SUMS ) && echo "   all files OK"
grep -E '^(built|git revision):|cilium/cilium:' "vodafone-idnow-$NAME/BUNDLE.txt" | cut -d@ -f1
df -h /var/lib "$B" | sed 's/^/   /'
step "done: $B/vodafone-idnow-$NAME ready. Next: ./upgrade.sh $NAME <rollback-name>"
