#
# Copyright 2012,2016 Cumulus Networks Inc.
#
# Common functions used by the cl-img-XXX commands
#
# This assumes the shell is ash/dash.
#

INIT_CONF=/usr/share/cumulus/img/platform

_log_msg()
{
	if [ "$quiet" = "y" ]; then return; fi
	printf "$@"
}

log_success_msg()
{
	_log_msg "Success: $@\n"
}

log_failure_msg()
{
	_log_msg "Failure: $@\n"
}

log_warning_msg()
{
	_log_msg "Warning: $@\n"
}

log_begin_msg()
{
	_log_msg "$@..."
}

log_end_msg()
{
	_log_msg "done.\n"
}

alt_config_dir=
active_config_dir=
active=
alt_image=
cl_check_env() 
{
    check_root_user=$1

    . $INIT_CONF/platform.conf

    if [ "$check_root_user" = "root-priv" ] ; then
        # init operations in this clause require root privs
        ID=$(id -u)
        [ $ID -eq 0 ] || {
            base=$(basename $0)
            log_warning_msg "${base}:  You must have root privileges to run this command."
            exit 1
        }

    fi
}

##
## cl_get_args() -- Process common arguments
##
help=n
verbose=n
image=
std_help_brief="[-h] [-v]"
std_help_args=$(cat<<EOF

-h
	Show this help message.

-v
	Be verbose.
EOF
)
cl_args="hv"
cl_arg_shift=
cl_get_args()
{
    while getopts "$cl_args" a ; do
        case $a in
            h)
                help=y
                ;;
            v)
                verbose=y
                ;;
            \?)
                log_failure_msg "Unexpected command option."
                cl_usage_short
                exit 1
                ;;
        esac
    done
    
    if [ "$help" = "y" ] ; then
        cl_usage
        exit 0
    fi

    cl_arg_shift=$(( $OPTIND - 1 ))
}

##
## Allow upper layers to search for additional arguments
##
cl_add_arg()
{
    cl_args="${cl_args}$1"
}

##
## Print the command usage to stdout via the pager
##
## Depends on externally declared std_help_brief, help_brief,
## help_summay, help_args, std_help_args and help_body strings.
##
cl_usage()
{
    cmd_name=$(basename $0)

    (
        printf -- "usage: $cmd_name $std_help_brief $help_brief\n"
        [ -n "$help_summary" ] && printf -- "$help_summary\n"
        [ -n "$help_args" ] && printf -- "\n$help_args\n"
        printf -- "$std_help_args\n"
        [ -n "$help_body" ] && printf -- "\n$help_body\n"
    ) | pager

}

##
## Echo short usage
##
## Depends on externally declared std_help_brief and help_brief.
##
cl_usage_short()
{
    cmd_name=$(basename $0)
    _log_msg "usage: $cmd_name $std_help_brief $help_brief\nUse -h for more help.\n"
}

##
## Run shell commands and log failures
##
retval=0
cl_run()
{
    if [ "$verbose" = "y" ] ; then
        echo "Running command: $@" > /dev/stderr
    fi
    eval "$@"
    retval=$?
    if [ $retval -ne 0 ] ; then
        log_failure_msg "Command failed: $@"
    fi

    return $retval
}

cl_prompt_yes_no()
{
    msg_str=$1

    echo -n "$msg_str (y/N)? "
    read ans
    if [ "$ans" = "y" ] || [ "$ans" = "Y" ]; then
	return 0
    fi
    return 1
}
