#! /bin/zsh

target_dir="/home/chris/.local/share/Dungeondraft/asset_packs"
download_dir="/home/chris/Downloads"

for file in $download_dir/FA_(Objects|Textures)_*.zip; do
    dir=$(mktemp -d)
    unzip -qq $file -d $dir

    extracted=$(find "$dir" -type f -name "*.dungeondraft_pack")

    if [[ -z "$extracted" ]]; then
        echo "No .dungeondraft_pack file found in the ZIP."
        rm -rf "$dir"
        exit 1
    fi

    echo "Extracted file: $extracted"

    # Extract the version number from the filename
    file=$(basename "$extracted")
    basename=$(echo "$file" | grep -oP '^FA_[^_]+_[^_]+')
    version_rx="v([0-9]+\.[0-9]+)"
    if [[ "$file" =~ v([0-9]+\.[0-9]+) ]]; then
        new_version=${match[1]}
    else
        echo "Could not extract version number from filename."
        rm -rf "$fir"
        continue
    fi

    echo "New version detected: $new_version"

    # Check for an existing file in the target directory
    existing=$(ls "$target_dir"/"${basename}"_v*.dungeondraft_pack 2>/dev/null | head -n 1)

    if [[ -n "$existing" ]]; then
        existing_filename=$(basename "$existing")
        if [[ "$existing_filename" =~ v([0-9]+\.[0-9]+) ]]; then
            existing_version=${match[1]}
        fi

        echo "Existing file found: $existing_filename (Version: $existing_version)"

        if [[ "$existing_version" == "$new_version" ]]; then
            echo "Same version already exists. No action taken."
            rm -rf "$dir"
            exit 0
        else
            echo "Different version detected. Removing old version."
            rm -f "$existing"
        fi
    fi

    # Move the new file to the target directory
    mv "$extracted" "$target_dir"

    echo "File moved to $target_dir: $filename"

    # Clean up
    rm -rf "$dir"
done
