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

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PACKAGE_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
source "$SCRIPT_DIR/lib/common.sh"

ARTIFACT_ROOT=""
OUTPUT_DIR="$PACKAGE_ROOT/dist"
while [ "$#" -gt 0 ]; do
  case "$1" in
    --artifact-root) ARTIFACT_ROOT="$2"; shift 2 ;;
    --output-dir) OUTPUT_DIR="$2"; shift 2 ;;
    *) die "unknown argument: $1" ;;
  esac
done

[ -n "$ARTIFACT_ROOT" ] || die "--artifact-root is required"
VERSION="$(tr -d '\r\n' < "$PACKAGE_ROOT/VERSION")"
STAGING="$(mktemp -d)"
trap 'rm -rf "$STAGING"' EXIT
TARGET="$STAGING/zhct-${VERSION}"
mkdir -p "$TARGET/artifacts/runtime" "$TARGET/artifacts/code" "$TARGET/evidence"

tar -C "$PACKAGE_ROOT" \
  --exclude='./artifacts' --exclude='./dist' --exclude='./evidence' \
  --exclude='__pycache__' --exclude='*.pyc' \
  -cf - . | tar -C "$TARGET" -xf -

for artifact_spec in \
  "lnmp2.2-from-git-20260706.tar.gz:9cdc130f859bfca6cbd138950128fda358b88fb1ebadad4f937ebc4560fe990b" \
  "redis-5.3.5.tgz:d55fa5cc699198917ba2bdc827da632ad77f009ba2642d2750456a976dbe5989" \
  "Mosquitto-0.4.0.tgz:eec599110f733afe5e0331a85d8feb354ec079b088bdca2dd81a587c5b50f8e4" \
  "supervisor-4.3.0-py2.py3-none-any.whl:0bcb763fddafba410f35cbde226aa7f8514b9fb82eb05a0c85f6588d1c13f8db"
do
  artifact_file="${artifact_spec%%:*}"
  artifact_sha="${artifact_spec#*:}"
  verify_sha256 "$ARTIFACT_ROOT/runtime/$artifact_file" "$artifact_sha"
  cp "$ARTIFACT_ROOT/runtime/$artifact_file" "$TARGET/artifacts/runtime/"
done

if find "$ARTIFACT_ROOT/code" -maxdepth 1 -type f -name '*.tgz' -print -quit | grep -q .; then
  cp "$ARTIFACT_ROOT"/code/*.tgz "$TARGET/artifacts/code/"
fi

find "$TARGET/scripts" "$TARGET/tools" -type f \( -name '*.sh' -o -name '*.py' \) -exec chmod 0755 {} +
mkdir -p "$OUTPUT_DIR"
OUTPUT="$OUTPUT_DIR/zhct-${VERSION}-online.tar.gz"
tar -C "$STAGING" -czf "$OUTPUT" "$(basename "$TARGET")"
printf '%s  %s\n' "$(sha256_file "$OUTPUT")" "$(basename "$OUTPUT")" > "$OUTPUT.sha256"
log "PACKAGE_READY output=$OUTPUT"
log "NOTE OS ISO is intentionally excluded because the target already runs licensed Kylin Desktop V10"
