#!/usr/bin/env bash
set -euo pipefail

ISO="linux-ai-1.0-star-cinnamon-amd64.iso"
PREFIX="${ISO}.part"
EXPECTED="17674146507f78a5724af5d69a7be1e36589e919f48673479e87c4d25118af91"

cd "$(dirname "$0")"

echo "Linux-AI OS ISO Rebuild Utility"
echo "================================"
echo

missing=0
for n in $(seq -w 0 13); do
    file="${PREFIX}${n}"
    if [[ ! -f "$file" ]]; then
        echo "MISSING: $file"
        missing=1
    fi
done

if [[ "$missing" -ne 0 ]]; then
    echo
    echo "ERROR: One or more download parts are missing."
    echo "Download all parts (part00 through part13) into this folder and run this script again."
    exit 1
fi

echo "All 14 parts are present."
echo "Rebuilding $ISO ..."
rm -f "$ISO"
cat "${PREFIX}"{00..13} > "$ISO"

echo
echo "Verifying SHA256 checksum..."
ACTUAL="$(sha256sum "$ISO" | awk '{print $1}')"

echo "Expected: $EXPECTED"
echo "Actual:   $ACTUAL"
echo

if [[ "$ACTUAL" == "$EXPECTED" ]]; then
    echo "============================================================"
    echo " SUCCESS!"
    echo
    echo " Linux-AI OS has been reconstructed successfully."
    echo " SHA256 VERIFIED"
    echo
    echo " Your ISO is ready:"
    echo " $ISO"
    echo "============================================================"
    exit 0
else
    echo "============================================================"
    echo " VERIFICATION FAILED"
    echo
    echo " The reconstructed ISO does NOT match the official checksum."
    echo " DO NOT use this ISO to create installation media."
    echo " Re-download any questionable or incomplete part and try again."
    echo "============================================================"
    exit 2
fi
