#!/bin/bash
# Build step: put the signed Saan packages under <dist>/packages and unpack the core payload to <dist>/app.
#   saan-fetch-release <local-packages-dir> <dist>
# Local packages (saan-core-*.zip, saan-mod-*.zip) win; otherwise SAAN_VERSION is downloaded from SAAN_RELEASE_BASE/feed.json and every
# file is checked against the SHA-256 and size in the feed (HTTPS). Every file of the core payload is then checked against the core
# manifest; the module packages are checked again (Ed25519 signature) by the app's own updater when they are installed.
set -euo pipefail
src=$1; dist=$2
mkdir -p "$dist/packages" "$dist/modules"
shopt -s nullglob
local_core=("$src"/saan-core-*.zip)
if [ ${#local_core[@]} -gt 0 ]; then
    [ ${#local_core[@]} -eq 1 ] || { echo "[ERR] more than one saan-core-*.zip in packages/" >&2; exit 1; }
    cp "$src"/saan-core-*.zip "$dist/packages/"
    for f in "$src"/saan-mod-*.zip; do cp "$f" "$dist/modules/"; done
    echo "[OK] local packages: $(basename "${local_core[0]}") + $(ls "$dist/modules" | wc -l) modules"
else
    base=${SAAN_RELEASE_BASE%/}
    curl -fsSL --proto '=https' --retry 3 -o /tmp/feed.json "$base/feed.json"
    v=$(jq -r '.core.version' /tmp/feed.json)
    [ "$v" = "$SAAN_VERSION" ] || { echo "[ERR] the feed offers core $v, this image is built for $SAAN_VERSION (set SAAN_VERSION or use local packages)" >&2; exit 1; }
    rel=$(jq -r '.base' /tmp/feed.json)
    get() { # name sha bytes target-dir
        curl -fsSL --proto '=https' --retry 3 -o "$4/$1" "$base/$rel$1"
        echo "$2  $4/$1" | sha256sum -c --quiet - || { echo "[ERR] SHA-256 mismatch: $1" >&2; exit 1; }
        [ "$(stat -c %s "$4/$1")" = "$3" ] || { echo "[ERR] size mismatch: $1" >&2; exit 1; }
    }
    get "$(jq -r '.core.zip' /tmp/feed.json)" "$(jq -r '.core.sha256' /tmp/feed.json)" "$(jq -r '.core.bytes' /tmp/feed.json)" "$dist/packages"
    jq -r '.modules[] | [.zip, .sha256, (.bytes|tostring)] | @tsv' /tmp/feed.json | while IFS=$'\t' read -r z s b; do get "$z" "$s" "$b" "$dist/modules"; done
    rm -f /tmp/feed.json
    echo "[OK] downloaded core $v + $(ls "$dist/modules" | wc -l) modules from $base"
fi
core=$(ls "$dist"/packages/saan-core-*.zip)
rm -rf /tmp/saan-x && mkdir /tmp/saan-x
unzip -q "$core" -d /tmp/saan-x
[ -f /tmp/saan-x/payload/artisan ] || { echo "[ERR] $core has no payload/artisan" >&2; exit 1; }
# every payload file must match its SHA-256 in the manifest, and nothing extra may be there
php -r '$m=json_decode(file_get_contents("/tmp/saan-x/manifest.json"),true);$n=0;foreach($m["files"] as $f){$p="/tmp/saan-x/payload/".$f["path"];if(!is_file($p)||hash_file("sha256",$p)!==$f["sha256"]){fwrite(STDERR,"[ERR] manifest mismatch: ".$f["path"]."\n");exit(1);}$n++;}
$all=0;foreach(new RecursiveIteratorIterator(new RecursiveDirectoryIterator("/tmp/saan-x/payload",FilesystemIterator::SKIP_DOTS)) as $x)if($x->isFile())$all++;
if($all!==$n){fwrite(STDERR,"[ERR] payload has $all files, manifest lists $n\n");exit(1);}echo "[OK] core manifest: $n files match\n";'
# packages built on Windows carry no Unix modes (unzip gives 0666): code must not be group/world writable (the updater refuses that)
find /tmp/saan-x/payload -type d -exec chmod 0755 {} +
find /tmp/saan-x/payload -type f -exec chmod 0644 {} +
rm -rf "$dist/app" && mv /tmp/saan-x/payload "$dist/app"
cp /tmp/saan-x/manifest.json "$dist/core-manifest.json"
rm -rf /tmp/saan-x
echo "[OK] core $(cat "$dist/app/VERSION") unpacked: $(find "$dist/app" -type f | wc -l) files"
