#!/usr/bin/env bash
# Run this script inside a server's ai_model directory:
#   bash ./mirror_ai_models.sh
# Keep ai_models.json beside this script.  Model files are downloaded into the
# current working directory, which is served by download/store/themes mirrors.

set -uo pipefail

SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"
CONFIG="${SCRIPT_DIR}/ai_models.json"
FORCE=0

if [[ "${1:-}" == "--force" ]]; then
    FORCE=1
fi

if [[ ! -f "$CONFIG" ]]; then
    echo "Model configuration was not found: $CONFIG" >&2
    exit 1
fi


if ! command -v python3 >/dev/null 2>&1; then
    echo "python3 is required to read ai_models.json." >&2
    exit 1
fi

if ! command -v curl >/dev/null 2>&1; then
    echo "curl is required. Install it with: sudo apt install curl" >&2
    exit 1
fi

# Emit filename<TAB>original publisher URL. Runtime downloads use only the
# Movie-Zilla mirrors; this server-only script seeds those mirrors.
while IFS=$'\t' read -r file_name source_urls; do
    [[ -z "$file_name" ]] && continue
    if [[ -z "$source_urls" ]]; then
        echo "[skip] $file_name has no upstream archive in ai_model_origins.json" >&2
        continue
    fi
    target="$PWD/$file_name"
    temporary="${target}.part"

    if [[ "$FORCE" -eq 0 && -s "$target" ]]; then
        echo "[skip] $file_name"
        continue
    fi

    rm -f -- "$temporary"
    echo "[get ] $file_name"
    downloaded=0
    read -r -a candidates <<< "$source_urls"
    for source_url in "${candidates[@]}"; do
        rm -f -- "$temporary"
        if curl --fail --location --retry 3 --retry-delay 3 --tlsv1.2 \
                --output "$temporary" "$source_url" && [[ -s "$temporary" ]]; then
            mv -f -- "$temporary" "$target"
            echo "[ ok ] $file_name ($source_url)"
            downloaded=1
            break
        fi
    done
    if [[ "$downloaded" -eq 0 ]]; then
        rm -f -- "$temporary"
        echo "[fail] $file_name could not be downloaded from its configured upstream" >&2
    fi
done < <(python3 - "$CONFIG" <<'PY'
import json
import sys

with open(sys.argv[1], encoding="utf-8") as config_file:
    config = json.load(config_file)
for model in config.get("models", []):
    file_name = model.get("file", "")
    if file_name:
        print(f"{file_name}\t{model.get('source', '')}")
PY
)
