#!/bin/sh

set -e

scriptname=$(basename $0)
scriptdir=$(cd $(dirname $0) && pwd)

. "$scriptdir/subr.sh"

# --------------------------------------------------------------------
# Read command line arguments.
# --------------------------------------------------------------------

usage() {
	cat <<EOF
$scriptname [OPTION]... <presets file>

Available options:
    -h         Display this usage.
    -l DB      Use DB as the library.db database.
    -P PREFIX  Prepend PREFIX to presets' name.
EOF
}

while getopts ":hl:P:" opt; do
	case $opt in
	h)
		usage
		exit 0
		;;
	l)
		database=$OPTARG
		;;
	P)
		label_prefix=$OPTARG
		;;
	esac
done
shift $((OPTIND-1))

profile=$1

# Check for required tools.
echo "===> Check for required tools"
missing_tool=0

if ! database_tools_installed; then
	missing_tool=1
fi
if ! internal_tools_available; then
	missing_tool=1
fi

if [ "$missing_tool" = "1" ]; then
	exit 1
fi

# Use main database by default.
if [ -z "$database" ]; then
	database="$HOME/.config/darktable/library.db"
fi

# --------------------------------------------------------------------
# Main code.
# --------------------------------------------------------------------

if [ ! -f "$profile" ]; then
	echo 1>&2
	echo "Cannot open presets file: $profile" 1>&2
	exit 1
fi

awk -f "$scriptdir/extract-values-from-presets.awk" < "$profile" | while read line; do
	set -- $line
	add_profile "$database" "$label_prefix" "$@"
done
