#!/usr/bin/bash
set -euo pipefail
IFS=$'\n\t'

DOWNLOAD_URL="https://download.mozilla.org/?product=firefox-devedition-latest-ssl&os=linux64"

APP_DIR_PATH=`dirname ${XDG_DATA_HOME:-~/.local/share}`/opt/firefox-developer-edition
APP_EXEC_PATH=$APP_DIR_PATH/firefox

APP_PREFS_DIR_PATH=$APP_DIR_PATH/browser/defaults/preferences
CUSTOM_PREFS_PATH=`systemd-path system-shared`/firefox-developer-edition/copr-mushrooms-default-prefs.js

show_notification()
{
    if [[ -n "${3:-}" ]]; then
        notify-send $1 $2 --icon firefox-developer-edition \
            --hint string:sound-name:dialog-error --urgency critical
    else
        notify-send $1 $2 --icon firefox-developer-edition \
            --hint string:sound-name:message-new-instant --hint int:transient:1
    fi
}

download_and_install_app()
{
    rm -rf $APP_DIR_PATH
    mkdir -p $APP_DIR_PATH

    show_notification "Firefox Developer Edition will start shortly" "Please wait for download…"

    curl $DOWNLOAD_URL -sL | bsdtar -C $APP_DIR_PATH --strip-components=1 -xf - || error="1"

    if [[ -n "${error:-}" ]]; then
        show_notification "Firefox Developer Edition cannot be started" "There is a problem with download!" "1"

        rm -rf $APP_DIR_PATH
        exit
    fi

    mkdir -p $APP_PREFS_DIR_PATH
    ln -sf $CUSTOM_PREFS_PATH $APP_PREFS_DIR_PATH/
}

main()
{
    if [[ ! -f $APP_EXEC_PATH ]]; then
        download_and_install_app
    fi

    exec $APP_EXEC_PATH $@
}

main $@
