#!/usr/bin/env bash

set -o errexit -o pipefail

OVERLAY=true

profile="$(TMPDIR="${HOME}/.local/tmp" mktemp -d -t "firefox.XXXXXXXXXX")"

FIREFOX_DEFAULT_PROFILE="j56dvo43.default-1520714705340"

case "$1" in
    "default")
        profile_source_directory="${HOME}/.mozilla/firefox/${FIREFOX_DEFAULT_PROFILE}"
        if [[ $OVERLAY == true ]]
        then
            overlay_rw_directory="$(TMPDIR="${HOME}/.local/tmp" mktemp -d -t "overlay.XXXXXXXXXX")"
            upper_directory="${overlay_rw_directory}/upper"
            workdir_directory="${overlay_rw_directory}/work"
            trap "set +e; sudo umount '$profile'; rmdir '$profile'; sudo rm -rf '$overlay_rw_directory'" EXIT
            mkdir -p "$upper_directory"
            mkdir -p "$workdir_directory"
            sudo mount -t overlay overlay -o "lowerdir=${profile_source_directory},upperdir=${upper_directory},workdir=${workdir_directory}" "$profile"
        else
            trap 'rm -rf "$profile"' EXIT
            rsync --archive "${profile_source_directory}/" "${profile}/"
        fi
        ;;
esac

firefox --new-instance --profile "$profile" "$@"
