#!/bin/sh

# Parameter Description:
# $1: Configuration file (mandatory parameter)
# $2: Optional parameter that specifies the path to the ipfixprobe library directory.
# If this parameter is not provided, the default value "/usr/lib/ipfixprobe" will be used.

CONFFILE="/etc/ipfixprobe/$1.conf"

# Help function to display usage instructions
show_help() {
    echo "Usage: $0 CONFIG_NAME [LIBRARY_PATH]"
    echo ""
    echo "CONFIG_NAME: Name of the configuration file (without the '.conf' extension)."
    echo "             The full path will be '/etc/ipfixprobe/[CONFIG_NAME].conf'."
    echo "LIBRARY_PATH: Optional path to the ipfixprobe library directory."
    echo "              If not provided, the default value '/usr/lib/ipfixprobe' will be used."
    echo ""
    echo "Example 1: Use the default library path:"
    echo "    $0 [name]"
    echo ""
    echo "Example 2: Specify a custom library path:"
    echo "    $0 [name] /usr/local/lib/ipfixprobe"
    echo ""
}

# Check if the user asked for help
if [ "$1" = "--help" ] || [ "$1" = "-h" ]; then
    show_help
    exit 0
fi

if [ -e "$CONFFILE" ]; then
	if grep -q 'INPUT\[' $CONFFILE; then
		echo "WARNING: Legacy configuration format detected. This format is obsolete and was already removed in the Alpine Linux package." >&2
		echo "Please transition to the new YAML configuration format. For more details, visit: https://github.com/CESNET/ipfixprobe/blob/master/init/link0.conf.example" >&2
		exit 1
	else
		IPFIXPROBE_LIB_DIR="${2:-/usr/lib/ipfixprobe}"
		command=$(python3 $IPFIXPROBE_LIB_DIR/config2args.py --config $CONFFILE --schema $IPFIXPROBE_LIB_DIR/schema.json)
		status=$?

		if [ $status -ne 0 ]; then
			echo "Cannot convert yaml config" >&2
			echo "$command" >&2
			exit $status
		fi
		eval "exec $command"
	fi
else
	echo "Error: Configuration file '$CONFFILE' does not exist, exitting." >&2
	show_help
	exit 1
fi

exit 0
