#!/bin/sh
set -eu

. ./log_utils.sh
. ./string_utils.sh
. ./check_system_configs.sh
. ./check_kernel_configs.sh
. ./check_cgroups.sh
. ./check_sw_packages.sh
. ./validate_platform_security.sh
. ./check_ggc_user_and_group.sh
. ./check_script_dependencies.sh

GGC_VERSION="1.6"
KERNEL_CONFIG_FILE=""
SCRIPT_USAGE_GUIDE="usage.txt"

print_help() {
    echo "Usage:"
    echo "sudo ./check_ggc_dependencies"
    echo "    [ --log-level  <LOG_LEVEL> | -log-level <LOG_LEVEL> ]"
    echo "    [ -h | --help | -help ]"
    echo "    [ -v | --version | -version ]"
    echo "    [ --kernel-config-file  <KERNEL_CONFIG_PATH>  | -kernel-config-file  <KERNEL_CONFIG_PATH> ]"
    echo ""
    echo "LOG_LEVEL must be one of:"
    echo "    DEBUG, WARN (default), INFO, ERROR and FATAL"
    echo ""
    echo "--version prints the version of Greengrass for which this script checks dependencies"
    echo ""
    echo "KERNEL_CONFIG_PATH is the absolute/relative path of the kernel config file"
    echo ""
    echo "Note that options can be specified with -- or -"
    echo "Eg: --version or -version, --log-level or -log-level"
}

parse_cmdline() {
    while [ "$#" -gt 0 ]
    do
        case "$1" in
            --log-level | -log-level )
                shift
                set_verbosity "$1"
                ;;

            -h | --help | -help )
                print_help
                exit 0
                ;;

            -v | --version | -version )
                ## The version of Greengrass core for which this script will
                ## check dependencies
                $PRINTF "Greengrass core version: $GGC_VERSION\n"
                exit 0
                ;;

            --kernel-config-file | -kernel-config-file )
                shift
                KERNEL_CONFIG_FILE="$1"
                ;;

            * )
                echo "Unknown option: $1"
                print_help
                exit 1
                ;;
        esac
        shift
    done
}

check_ggc_dependencies() {
    info "========================Dependency check report for GGC v$GGC_VERSION========================="
    check_system_configs
    check_kernel_configs "$KERNEL_CONFIG_FILE"
    check_cgroups_mounted
    check_sw_packages
    validate_platform_security
    check_ggc_user_and_group_exist
    print_results "$GGC_VERSION"
    info "===================================================================================="
}

parse_cmdline $@
check_script_dependencies "$0"