#! /bin/bash
# vim: fdm=marker et

. shell-args

# function show_help {{{
show_help()
{
    cat <<EOF

mkve-template - create a skeleton template for mkve-bundle

Usage: $PROG [options] <template>

Options:
  --hypervisor=HYPERVISOR   hypervisor (type of virtualization);
  --append                  <template> is already support an another <hypervisor>;
  -q, --quiet               try to be more quiet;
  -v, --verbose             try to be more verbose;
  -V, --version             print program version and exit;
  -h, --help                show help text and exit.

See mkve-template(1) for more verbose help.
EOF

    exit 0
}
# }}}
# function check_variables {{{

# function check_template {{{

# This function checks that our's argument is a valid writable directory
check_template()
{
    [ -n "$template" ] ||
        fatal "template is not specified"

    if [ -z "$append" ]; then
        mkdir -p "$template" ||
        fatal "can't create directory $template"
    fi

    verbose "using template '$template'"
}
# }}}
# function check_hypervisor {{{

# This function checks that it's argument is a valid hypervisor
check_hypervisor()
{
    [ -n "$hypervisor" ] ||
        fatal "hypervisor is not specified"

    if [ -n "$append" ]; then
        egrep -q "^$hypervisor$" "$template/hypervisors" ||
            fatal "already supported hypervisor: $hypervisor"
    fi

    verbose "using hypervisor '$hypervisor'"
}
# }}}

check_variables()
{
    check_template
    check_hypervisor
}
# }}}
# function create_hypervisors {{{
create_hypervisors()
{
    echo "$hypervisor" >>"$template/hypervisors" ||
        fatal "can't write to $template/hypervisors"
}
# }}}
# function create_version {{{
create_version()
{
    mkdir -p "$template/versions"
    echo "template_version=0.01" >"$template/versions/$hypervisor" ||
        fatal "can't write to $template/versions/$hypervisor"
}
# }}}
# function create_packages_list {{{
create_packages_list()
{
    mkdir -p "$template/packages-lists"
    echo "ve-$(basename "$template")" >"$template/packages-lists/$hypervisor" &&
    echo "ve-hypervisor-$hypervisor" >>"$template/packages-lists/$hypervisor" ||
        fatal "can't write $template/packages-lists/$hypervisor"
}
# }}}

append=

TEMP=$(getopt -o ${getopt_common_opts} -n "$PROG" --long hypervisor:,append,${getopt_common_longopts} -- "$@")
eval set -- "${TEMP}"
while true; do
    case "$1" in
        --hypervisor)
            shift; hypervisor="$1"
            ;;
        --append)
            append='yes'
            ;;
        --) shift; break
            ;;
        *)
            parse_common_option "$1"
            ;;
    esac
    shift
done

template="$1"

check_variables
create_hypervisors
create_version
create_packages_list
