#!/usr/bin/bash
lock_file='/var/www/html/thewarren.co.za/services/set_import.lock'
zip_file='/var/www/html/thewarren.co.za/mtg_importer/all_sets/AllSetFiles.zip'
target_dir='/var/www/html/thewarren.co.za/mtg_importer/all_sets'
download_url='https://mtgjson.com/api/v5/AllSetFiles.zip'

touch "$lock_file"

# Clean out old JSON files
rm -f "$target_dir"/*.json

# Download: if file doesn't exist, download normally; else, use --timestamping
if [ ! -f "$zip_file" ]; then
    wget "$download_url" --directory-prefix="$target_dir"
else
    wget -N "$download_url" --directory-prefix="$target_dir"
fi

# Unzip and clean up
unzip -o "$zip_file" -d "$target_dir"
rm -f "$zip_file"

# Change to the working directory
cd "$target_dir" || {
#    echo "Error: Could not change to directory $target_dir"
    exit 1
}
 
# Loop through all .json files in the working directory
for file in *.json; do
    # Check if the file exists to avoid errors with no matching files
    if [[ -f "$file" ]]; then
        # Get the filename without the .json extension
        base_name=$(basename "$file" .json)
        # Check if the filename ends with an underscore
        if [[ "$base_name" == *_ ]]; then
            # Remove the trailing underscore and add .json back
            new_name="${base_name%_}.json"
            # Rename the file with full paths
            mv -v "$target_dir/$file" "$target_dir/$new_name"
        fi
    fi
done

rm -f "$lock_file"