#!/bin/bash
set -euo pipefail

if [ -z "${1:-}" ]; then
    echo "Usage: $0 <version>"
    echo "Example: $0 0.25"
    exit 1
fi

VERSION="$1"
BASEDIR="$(cd "$(dirname "$0")" && pwd)"
VERSION_DIR="$BASEDIR/$VERSION"

if [ ! -d "$VERSION_DIR" ]; then
    echo "Error: directory $VERSION_DIR does not exist"
    exit 1
fi

RELEASE_DATE=$(date -u +"%Y-%m-%dT%H:%M:%S.%3NZ")

echo "=== Building latest.json for version $VERSION ==="

# Start JSON object
JSON=$(jq -n --arg v "$VERSION" --arg d "$RELEASE_DATE" '{version: $v, files: {}, releaseDate: $d}')

# Walk os/arch/file structure
for os_dir in "$VERSION_DIR"/*/; do
    [ -d "$os_dir" ] || continue
    os_name=$(basename "$os_dir")

    for arch_dir in "$os_dir"/*/; do
        [ -d "$arch_dir" ] || continue
        arch_name=$(basename "$arch_dir")

        FILES="[]"
        for file in "$arch_dir"/*; do
            [ -f "$file" ] || continue
            fname=$(basename "$file")
            sha=$(sha512sum "$file" | awk '{print $1}')
            sz=$(stat -c%s "$file")
            url="$VERSION/$os_name/$arch_name/$fname"

            FILES=$(echo "$FILES" | jq \
                --arg u "$url" --arg s "$sha" --arg sz "$sz" \
                '. + [{"url": $u, "sha512": $s, "size": $sz}]')

            echo "  $url  size=$sz"
        done

        JSON=$(echo "$JSON" | jq \
            --arg os "$os_name" --arg arch "$arch_name" --argjson f "$FILES" \
            '.files[$os][$arch] = $f')
    done
done

# 1) Write latest.json inside version directory
echo "$JSON" | jq '.' > "$VERSION_DIR/latest.json"
echo "=> Created $VERSION_DIR/latest.json"

# 2) Recreate latest/ directory with contents of version directory
LATEST_DIR="$BASEDIR/latest"
rm -rf "$LATEST_DIR"
mkdir -p "$LATEST_DIR"
# Copy only the os subdirectories (not latest.json) to keep it clean
for os_dir in "$VERSION_DIR"/*/; do
    [ -d "$os_dir" ] || continue
    cp -r "$os_dir" "$LATEST_DIR/"
done
# Also copy latest.json into latest/
cp "$VERSION_DIR/latest.json" "$LATEST_DIR/latest.json"
echo "=> Recreated $LATEST_DIR/ with files from $VERSION_DIR/"

# 3) Copy latest.json to parent level
cp "$VERSION_DIR/latest.json" "$BASEDIR/latest.json"
echo "=> Copied latest.json to $BASEDIR/latest.json"

echo "=== Done ==="
