#!/bin/bash
### @accetto (https://github.com/accetto) (https://hub.docker.com/u/accetto/)

# ARG_OPTIONAL_SINGLE([source],[s],[Source folder (where 'user.js' is).],[/home/headless/firefox.plus])
# ARG_OPTIONAL_SINGLE([target],[t],[Target folder (where Firefox profiles are).],[/home/headless/.mozilla/firefox])
# ARG_VERSION([echo $0 v19.06.08])
# ARG_HELP([Copy 'user.js' into existing Firefox profiles])
# ARGBASH_GO()
# needed because of Argbash --> m4_ignore([
### START OF CODE GENERATED BY Argbash v2.8.0 one line above ###
# Argbash is a bash code generator used to get arguments parsing right.
# Argbash is FREE SOFTWARE, see https://argbash.io for more info


die()
{
	local _ret=$2
	test -n "$_ret" || _ret=1
	test "$_PRINT_HELP" = yes && print_help >&2
	echo "$1" >&2
	exit ${_ret}
}


begins_with_short_option()
{
	local first_option all_short_options='stvh'
	first_option="${1:0:1}"
	test "$all_short_options" = "${all_short_options/$first_option/}" && return 1 || return 0
}

# THE DEFAULTS INITIALIZATION - OPTIONALS
_arg_source="/home/headless/firefox.plus"
_arg_target="/home/headless/.mozilla/firefox"


print_help()
{
	printf '%s\n' "Copy 'user.js' into existing Firefox profiles"
	printf 'Usage: %s [-s|--source <arg>] [-t|--target <arg>] [-v|--version] [-h|--help]\n' "$0"
	printf '\t%s\n' "-s, --source: Source folder (where 'user.js' is). (default: '/home/headless/firefox.plus')"
	printf '\t%s\n' "-t, --target: Target folder (where Firefox profiles are). (default: '/home/headless/.mozilla/firefox')"
	printf '\t%s\n' "-v, --version: Prints version"
	printf '\t%s\n' "-h, --help: Prints help"
}


parse_commandline()
{
	while test $# -gt 0
	do
		_key="$1"
		case "$_key" in
			-s|--source)
				test $# -lt 2 && die "Missing value for the optional argument '$_key'." 1
				_arg_source="$2"
				shift
				;;
			--source=*)
				_arg_source="${_key##--source=}"
				;;
			-s*)
				_arg_source="${_key##-s}"
				;;
			-t|--target)
				test $# -lt 2 && die "Missing value for the optional argument '$_key'." 1
				_arg_target="$2"
				shift
				;;
			--target=*)
				_arg_target="${_key##--target=}"
				;;
			-t*)
				_arg_target="${_key##-t}"
				;;
			-v|--version)
				echo $0 v19.06.08
				exit 0
				;;
			-v*)
				echo $0 v19.06.08
				exit 0
				;;
			-h|--help)
				print_help
				exit 0
				;;
			-h*)
				print_help
				exit 0
				;;
			*)
				_PRINT_HELP=yes die "FATAL ERROR: Got an unexpected argument '$1'" 1
				;;
		esac
		shift
	done
}

parse_commandline "$@"

# OTHER STUFF GENERATED BY Argbash

### END OF CODE GENERATED BY Argbash (sortof) ### ])
# [ <-- needed because of Argbash

_counter=0
_file_userjs="user.js"
_file_profilesini="profiles.ini"
_full_userjs=""
_full_profilesini=""
_input=""
_line=0
_mark=""
_oldIFS=""
declare -a _list

# DEBUG=true

[[ $DEBUG ]] && _arg_source="."
[[ $DEBUG ]] && _arg_target="../.mozilla/firefox"

fn_die()
{
	local _ret=$2
	test -n "$_ret" || _ret=1
	test "$_PRINT_HELP" = yes && print_help >&2
	echo "$1" >&2
	read -rp $"Press any key to close this window ... " -n1 _input
	exit ${_ret}
}

### source and target folders must be provided
# : ${_arg_source?} ${_arg_target?}
[[ ! ${_arg_source} ]] && fn_die "Source path must be provided!"
[[ ! ${_arg_target} ]] && fn_die "Target path must be provided!"

_full_userjs="${_arg_source}/${_file_userjs}"
_full_profilesini="${_arg_target}/${_file_profilesini}"

### source folder must contain 'user.js'
[[ -f "${_full_userjs}" ]] && echo "File '${_full_userjs}' exists." || fn_die "FAILED: File '${_full_userjs}' not found!"

### target folder must contain 'profiles.ini'
[[ -f ${_full_profilesini} ]] && echo "File '${_full_profilesini}' exists." || fn_die "FAILED: File '${_full_profilesini}' not found!"

### only profiles in 'profiles.ini' will be processed, get their count
_counter=$( grep -c -E '^Path=' "${_full_profilesini}" )

if [[ $_counter -gt 0 ]] ; then

	### extract profile folder names from 'profiles.ini' into the array
	### be aware that user profile names/folders can contain spaces
	_oldIFS=$IFS
	IFS=$'\x0A'$'\x0D'
	_list=( $( grep -E '^Path=' "${_full_profilesini}" | sed -E -e 's/^Path=//' ) )
	IFS=$_oldIFS

	echo "Following profiles found in '${_file_profilesini}' ('+|-' means with/without '${_file_userjs}'):"
	_counter=0
	for p in "${_list[@]}" ; do
		_counter=$((${_counter}+1))
		[[ $(ls "${_arg_target}/$p/${_file_userjs}" 2>/dev/null) ]] && _mark=" + " || _mark=" - "
		printf '     %s %s  %s\n' "$_counter" "$_mark" "$p"
	done

	### user interaction
	read -rp $"Into which profile to copy '${_file_userjs}' (line number or 'all')? " _input
	_input=$(echo ${_input,,} | grep -i -E "^[0-9]+$|^all$")
	[[ ! ${_input} ]] && fn_die "INTERRUPTED: Line number or 'all' required!"
	if [[ "${_input,,}" != "all" ]] ; then

		### line number has been provided
		_line=${_input}
		[[ ${_line} -lt 1 || ${_line} -gt ${_counter} ]] && fn_die "FAILED: Line number must be from the interval [1..${_counter}]!"
		_line=$((${_line}-1))

		### copy 'user.js' into the selected profile folder
		cp -v "${_full_userjs}" "${_arg_target}/${_list[${_line}]}/"

	else
		# 'all' has been provided
		### copy 'user.js' into all profiles not containing it yet
		for p in "${_list[@]}" ; do
			cp -v "${_full_userjs}" "${_arg_target}/$p/"
		done
	fi

	fn_die "SUCCESS." 0
else
	echo "No profiles found in '${_full_profilesini}'."
fi

fn_die "" 0

# ] <-- needed because of Argbash
