#!/bin/bash

set -e

export TERM=linux							  # make sure we're using a known terminal type
export TEXTDOMAIN=ltsp                        # gettext domain (.mo file name)
export TEXTDOMAINDIR=/usr/share/locale        # locale dir for gettext codes

VENDOR=$(lsb_release -i -s)
export BASE=${BASE:-/opt/ltsp}                       # LTSP base directory
MODULES_BASE=${MODULES_BASE:-/usr/share/ltsp} # our modules place
PLUGINS_BASE=$MODULES_BASE/plugins            # base plugin repository
SCRIPT=ltsp-build-client
PLUGIN_DIRS="/etc/ltsp/plugins/$SCRIPT $PLUGINS_BASE/$SCRIPT/$VENDOR-custom $PLUGINS_BASE/$SCRIPT/$VENDOR $PLUGINS_BASE/$SCRIPT/common"

KMODULES=${KMODULES:-"mousedev psmouse"}      # kernel modules for automatic loading

PARAMS="config:"                              # store commandline params for getopt
HELP_MESSAGE=""                               # store regular help messages
ADVANCED_HELP_MESSAGE=""                      # store advanced help messages

. gettext.sh

# load plugin functions
. $PLUGINS_BASE/functions

##################################
### Methods to be called by plugins
##################################

# Add an option for commandline parser
#
# Params:
# $1 - param name
# $2 - help message
# $3 - regular|advanced
# $4 - has a value? (true or false)
add_option () {
    case $4 in
    true)
        NAME="opt_with_param_$(echo $1 | tr '-' '_')"
        eval "$NAME"=true
        PARAMS="$PARAMS,$1:"
        ;;
    false)
        PARAMS="$PARAMS,$1"
        ;;
    *)
        echo "`eval_gettext "API ERROR: you need to provide true or false."`"
        ;;
    esac

    MESSAGE=$(printf "   --%-24s %s" "$1" "$2")
    if [ $3 = regular ]; then
        HELP_MESSAGE="$HELP_MESSAGE $MESSAGE\n"
    else
        ADVANCED_HELP_MESSAGE="$ADVANCED_HELP_MESSAGE $MESSAGE\n"
    fi
}

# Print if using debug.
#
# Params:
# $* - message to be print
debug() {
    if [ -n "$DEBUG" ]; then
        echo "DEBUG: $@" > /dev/stderr
    fi
}

# Use it to mount thing on chroot and those will be automaticaly
# unmounted when exit.
#
# Params:
# $1 - what to mount
# $2 - where to mount (skip the chroot path)
# $3 - mount extra params
chroot_mount() {
    if mount $3 $1 $ROOT/$2; then
        CHROOT_MOUNTED="$CHROOT_MOUNTED $ROOT/$2"
    fi
}

####################################
### End of plugins public methods
####################################

# Add commandline option to handle --help
add_option "help" "`eval_gettext "Display this help message"`" "regular" "false"
add_option "extra-help" "`eval_gettext "Display help for all available commandline options"`" "regular" "false"

# Print usage information.
usage() {
    echo `eval_gettext "LTSP Build Client usage:"`
    echo
    echo "  ltsp-build-client <options>"
    echo
    echo -n `eval_gettext "  Regular options:"`
    echo -e "$HELP_MESSAGE" | sort
    if [ "$ADVANCED_HELP" = "true" ]; then
        echo
        echo -n `eval_gettext "  Advanced options:"`
        echo -e "$ADVANCED_HELP_MESSAGE" | sort
    fi
}

# Clean up the chroot and exit.
on_exit() {
    for dir in $CHROOT_MOUNTED ; do
        umount $dir
    done

    if [ true = "$run_successfull" ] ; then
        echo "`eval_gettext "info: LTSP client installation completed successfully"`"
    else
        echo "`eval_gettext "error: LTSP client installation ended abnormally"`"
        exit 1
    fi
}

load_plugins 'commandline'

# Parse the commandline options
if ! TEMP=`getopt -o '' --long $PARAMS -n "$0" -- "$@"`; then
    usage >&2; exit 1; 
fi
eval set -- "$TEMP"

if [ "--config" = "$1" ] && [ -n "$2" ]; then
    . "$2"
    test "$#" -gt 1 && shift 2
elif [ -f /etc/ltsp/ltsp-build-client.conf ]; then
    . /etc/ltsp/ltsp-build-client.conf
fi

while [ ! -z "$1" ] && [ "$1" != "--" ]; do
    OPTION=$(echo ${1:2} | tr "-" "_") # remove -- from variable name
    shift
    NAME="opt_with_param_$OPTION"
    VARIABLE=option_${OPTION}_value
    if [ "${!NAME}" = true ]; then
        eval $VARIABLE=\"$1\"
        shift
    else
        eval $VARIABLE=true
    fi
done

if [ -n "$option_help_value" ] || [ -n "$option_extra_help_value" ]; then
    if [ -n "$option_extra_help_value" ]; then
        ADVANCED_HELP="true"
    fi
    usage
    exit 0
fi

trap on_exit EXIT

for hook in configure before-install install after-install finalization; do
    load_plugins "$hook"
done

run_successfull=true # report success to on_exit()

exit 0
