#!/bin/bash

# Export folder
export_folder="packaged"

# Name of the extension
extension_name="refused_to_be_human"

# Files to include in the package
include_files="fonts/texgyreheros-bolditalic.woff background.js checkUser.js content.js icon_OFF_48.png icon_ON_48.png LICENSE manifest.json rtbh_style.css"

# Get the current version using jq to parse JSON (if jq is available)
current_version=$(jq -r '.version' manifest.json)

# If jq is not available, fallback to a simpler grep (removing the -P flag)
# current_version=$(grep -o '"version": "[0-9.]*"' manifest_ff.json | grep -o '[0-9.]*')

# Split version into major, minor, and patch
IFS='.' read -r major minor patch <<< "$current_version"

# Increment the patch version by 1
new_patch=$((patch + 1))

# Format the new version
new_version="$major.$minor.$new_patch"

# Output the new version
echo "New version: $new_version"

# Update version in manifest.json, manifest_ff.json, and manifest_chrome.json
for file in manifest.json manifest_ff.json manifest_chrome.json; do
    if [ -f "$file" ]; then
        # Use jq to update the version in each JSON file
        jq --arg new_version "$new_version" '.version = $new_version' "$file" > tmp.json && mv tmp.json "$file"
        echo "Updated $file to version $new_version"
    else
        echo "$file not found, skipping..."
    fi
done

# Replace version number in manifest_ff.json and chrome
sed -i "s/\"version\": \"$current_version\"/\"version\": \"$new_version\"/" manifest_ff.json
sed -i "s/\"version\": \"$current_version\"/\"version\": \"$new_version\"/" manifest_chrome.json

folder_name="$extension_name-$new_version"

# Create a new folder with the extension name and version inside the export folder if it doesn't exist
if [ ! -d "$export_folder/$folder_name" ]; then
    mkdir -p "$export_folder/$folder_name"
    echo "Created folder: $export_folder/$folder_name"
else
    echo "Folder $export_folder/$folder_name already exists, skipping..."
fi

# prepping firefox xpi
cp background_ff.js background.js
cp content_ff.js content.js
cp manifest_ff.json manifest.json
zip "$export_folder/$folder_name/$extension_name-$new_version.xpi" $include_files

# prepping chrome file
cp background_chrome.js background.js
cp content_chrome.js content.js
cp manifest_chrome.json manifest.json
zip "$export_folder/$folder_name/$extension_name-$new_version.zip" $include_files

# setting back to chrome manifest
cp background_chrome.js background.js
cp content_chrome.js content.js
cp manifest_chrome.json manifest.json