#!/bin/sh

BADGES_DIR="/app/badges"
BADGES_JSON="$BADGES_DIR/badges.json"
IMAGES_DIR="$BADGES_DIR/badges"

migrated=0
failed=0

tmp_json=$(mktemp)
cp "$BADGES_JSON" "$tmp_json"

for userId in $(jq -r 'keys[]' "$BADGES_JSON"); do
    count=$(jq -r --arg id "$userId" '.[$id] | length' "$BADGES_JSON")
    i=0
    while [ $i -lt "$count" ]; do
        url=$(jq -r --arg id "$userId" --argjson i "$i" '.[$id][$i].badge' "$BADGES_JSON")
        tooltip=$(jq -r --arg id "$userId" --argjson i "$i" '.[$id][$i].tooltip' "$BADGES_JSON")

        case "$url" in
            *images.equicord.org*)
                ;;
            *)
                i=$((i + 1))
                continue
                ;;
        esac

        echo "Migrating: $url"

        download_url="$url"
        if [ "$tooltip" = "Equicord Donor" ] || [ "$tooltip" = "Suncord Donor" ]; then
            download_url="https://badge.equicord.org/donor.webp"
        fi

        tmp_file=$(mktemp)
        if ! curl -sL "$download_url" -o "$tmp_file"; then
            echo "  FAILED: download error"
            failed=$((failed + 1))
            rm -f "$tmp_file"
            i=$((i + 1))
            continue
        fi

        ext="${url##*.}"
        case "$ext" in
            png|jpg|jpeg|gif|webp|svg|apng)
                ;;
            *)
                ext="webp"
                ;;
        esac

        hash=$(sha1sum "$tmp_file" | cut -d' ' -f1)

        user_dir="$IMAGES_DIR/$userId"
        mkdir -p "$user_dir"

        filename="${hash}.${ext}"
        mv "$tmp_file" "$user_dir/$filename"

        new_url="https://badge.equicord.org/badges/$userId/$filename"

        jq --arg id "$userId" --argjson i "$i" --arg url "$new_url" \
            '.[$id][$i].badge = $url' "$tmp_json" > "${tmp_json}.new" && mv "${tmp_json}.new" "$tmp_json"

        echo "  -> $new_url"
        migrated=$((migrated + 1))

        i=$((i + 1))
    done
done

mv "$tmp_json" "$BADGES_JSON"

echo ""
echo "Done! Migrated: $migrated, Failed: $failed"
