#!/bin/sh

# Copyright (c) 2023, Natacha Porté
#
# Permission to use, copy, modify, and distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

PROFILE_DIR="${HOME}/tmp/profiles"

if test $# -lt 1; then
	firefox -no-remote -profilemanager
	exit
fi;

PROFILE=${1%[=-]}
TEMPLATE=${2:-Empty}

if test "${PROFILE}=" = "${1}"; then
	PROFILE_DIR="/tmp/profiles"
fi

if ! test -d "${PROFILE_DIR}/${PROFILE}"; then
	if test "${PROFILE}" = "${1}"; then
		echo -n "Profile ${PROFILE} doesn't exist, create it?"
		read ANSWER
	fi
	mkdir -p "${PROFILE_DIR}/${PROFILE}" || exit $?
	rsync -trlpgovDHq \
	    "${HOME}"/.mozilla/firefox/*."${TEMPLATE}"/ \
	    "${PROFILE_DIR}/${PROFILE}/" \
	    || exit $?
fi

# old exclusions:
#	    --exclude=bookmark* \
#	    --exclude=urlclassifier3.sqlite \
#	    --exclude=places.sqlite \
#	    --exclude=sessionstore* \
#	    --exclude=Cache \

if test -n "${TERM}"; then
	printf '\033]2;%s\007' "${PROFILE}"
fi

firefox -no-remote -profile "${PROFILE_DIR}/${PROFILE}" || PROFILE="$1"

if test -n "${TERM}"; then
	printf '\033]2;(%s)\007' "${PROFILE}"
fi

if ! test ${PROFILE} = $1; then
	rm -rf "${PROFILE_DIR}/${PROFILE}"
fi
