#!/bin/sh

set -e

PROFILE_DIR=~/.mozilla/firefox

DB_PATTERN="*/extension-data/ublock0.sqlite"
NEW_PATH="../browser-extension-data/uBlock0@raymondhill.net"

sqlite_to_json() {
    sqlite3 -separator "	" "$1" "SELECT * FROM settings;" \
        | awk 'BEGIN { FS="	"; printf "{" }
               !/^(cache\/|assetCacheRegistry|assetSourceRegistry|selfie|resourcesSelfie)/ { printf "\"%s\":%s,", $1, $2 }
               END { printf "}\n" }' \
        | sed -e 's/,}$/}/'
}

if ! command -v sqlite3 > /dev/null; then
    echo "Error: sqlite3 needed for migration."
    exit 1
fi

find "$PROFILE_DIR" -path "$DB_PATTERN" | while read -r DB_FILE
do
    BASEDIR=$(dirname "$DB_FILE")
    PROFILE_NAME=$(basename "$(dirname "$BASEDIR")")

    OUT_PATH="$BASEDIR/$NEW_PATH"
    OUT_FILE="$OUT_PATH/storage.js"

    echo "Found legacy ublock settings for profile: $PROFILE_NAME"

    if [ ! -e "$OUT_PATH" ]; then
        echo "New settings directory not found, creating.."
        mkdir -p "$OUT_PATH"
    fi

    if [ -e "$OUT_FILE" ]; then
        echo "New settings already exist, backing up to storage.js.old.."
        mv "$OUT_FILE" "$OUT_PATH/storage.js.old"
    fi

    echo "Converting legacy settings.."
    sqlite_to_json "$DB_FILE" > "$OUT_FILE"

    echo
done

echo "Done."
