#!/bin/bash

# BEGIN_ICS_COPYRIGHT8 ****************************************
#
# Copyright (c) 2015-2019, Intel Corporation
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
#     * Redistributions of source code must retain the above copyright notice,
#       this list of conditions and the following disclaimer.
#     * Redistributions in binary form must reproduce the above copyright
#       notice, this list of conditions and the following disclaimer in the
#       documentation and/or other materials provided with the distribution.
#     * Neither the name of Intel Corporation nor the names of its contributors
#       may be used to endorse or promote products derived from this software
#       without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
# END_ICS_COPYRIGHT8   ****************************************

# [ICS VERSION STRING: unknown]
# This script checks kernel version, rebuild kernel rpms when need and creates
# a local repo
#set -x

#==============================================================================#
# constants and variables
#------------------------------------------------------------------------------#

# success exit code
readonly SUCCESS=0
# user interrupted exit code
readonly USR_INT=1
# invalid argument exit code
readonly INV_ARGS=2
# wrong location exit code
readonly LOC_ERROR=3
# run time error exit code
readonly RT_ERROR=4

# function return states
readonly OK=1
readonly ERROR=0

# The following is resource string constants

# INSTALL script name
readonly S_INSTALL="INSTALL"
# repos folder name
readonly S_REPOS="repos"
# OFA DELTA name
readonly S_OFA_DELTA="IntelOPA-OFA_DELTA.*"
# OPA FM name
readonly S_FM="IntelOPA-FM.*"
# OPA Tools name
readonly S_TOOLS="IntelOPA-Tools-FF.*"
# OPA MPI name
readonly S_MPI="OFA_MPIS.*"
# OPA_PKGS repo rpms
readonly S_REPO_COMM_RPMS="OPA_PKGS/RPMS"
# OPA_PKGS_CUDA repo rpms
readonly S_REPO_CUDA_RPMS="OPA_PKGS_CUDA/RPMS"
# Repo ID for IFS pkg
readonly S_IFS_REPOID="IntelOPA-IFS"
# Repo Name for IFS pkg
readonly S_IFS_REPONAME="Intel OPA IFS Packages"
# Repo ID for Basic pkg
readonly S_BASIC_REPOID="IntelOPA-Basic"
# Repo Name for Basic pkg
readonly S_BASIC_REPONAME="Intel OPA Basic Packages"
# suffix for CUDA version repo
readonly S_CUDA_ID_SUFFIX="_CUDA"
readonly S_CUDA_NAME_SUFFIX=" With CUDA Support"
# mpi-selector
readonly S_MPI_SELECTOR="mpi-selector"
# sandia-openshmem
readonly S_SOS="sandia-openshmem"

# End of resource string constants

# log file path
readonly LOG_FILE="/var/log/opa.log"
# script file directory
readonly DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# script file name
readonly FNAME="${0##*/}"

# prior knowledge about management rpms

# the extra common rpms not found under S_FM
readonly -a MGT_EXT_COM_RPMS=( opa-fastfabric opa-mpi-apps )
# the extra RHEL rpms
readonly -a MGT_EXT_RHEL_RPMS=( opa-debuginfo )
# the extra SLES rpms
readonly -a MGT_EXT_SLES_RPMS=( opa-debugsource opa-fastfabric-debuginfo )

# end of prior knowledge

declare -i IS_BASIC=0
declare -i USE_YUM=0
declare -i USE_CUDA=0
declare -i USE_USER_KERS=0
declare -a KER_VERS
declare -a KER_RPMS
declare    REPO_ID
declare    REPO_NAME
declare    REPO_RPM_PATH
declare -a ALL_RPMS
declare -a MGT_RPMS
declare -a MPI_RPMS

function usage() {
    echo "Usage: ${FNAME} [-G]"
    echo "       ${FNAME} -i"
    echo "       ${FNAME} --help"
    echo
    echo "Create a local repo for Intel OPA IFS packages."
    echo
    echo "Options:"
    echo "  -G     create a repo with GPU Direct support (to install it"
    echo "         must have NVidia driver installed)"
    echo "  -i     display information about the repo it will create"
    echo
    echo "  --help produce full help text"
    echo
    echo "Examples:"
    echo "  ${FNAME}"
    echo "  ${FNAME} -G"
    echo "  ${FNAME} -i"
}

function log_msg() {
    echo "$1" >> ${LOG_FILE}
}

function print_msg() {
    echo "$1"
    log_msg "$1"
}

#############################################################################
# Print out error messages to STDERR and log file. Accepts multiple messages
# and will print them in the following format
# ERROR: $1
#        $2
#        ...
# Globals:
#   None
# Arguments:
#   messages
# Returns:
#   None
#############################################################################
function err() {
    echo "ERROR: $1" >&2
    log_msg "ERROR: $1"
    for msg in "${@:2}"; do
        echo "       ${msg}" >&2
        log_msg "       ${msg}"
    done
}

#############################################################################
# Print out script start messages in log file with similar information and
# in the same format as INSTALL script
# Globals:
#   None
# Arguments:
#   One extra line in the log file, it suppose to be script command arguments
# Returns:
#   None
#############################################################################
function log_script_start() {
    # print banner with 80 '-'s
    log_msg "$(printf "%0.s-" {1..80})"
    log_msg "${FNAME} Run $(date)"
    log_msg "$1"
    log_msg "Current Dir: $(pwd)"
}

#############################################################################
# Helper function run a command and put output on both console and log file
# Globals:
#   None
# Arguments:
#   $@ command and arguments to run
# Returns:
#   OK if successes
#   ERROR if fails
#############################################################################
function exec_and_log() {
    log_msg "+ $*"
    # reset IFS to retain the raw string
    local tmp=${IFS}
    IFS=
    local res
    # the following must to be in a separate line. If combine with above line
    # we cannot get correct exit code
    res="$($@)"
    local ret=$?
    if [[ -n "${res}" ]]; then
        print_msg "${res}"
    fi
    IFS=${tmp}

    if [[ ${ret} -ne 0 ]]; then
        return ${ERROR}
    else
        return ${OK}
    fi
}

function is_valid_location() {
    if [[ ! -e "${DIR}/${S_INSTALL}" ]]; then
        return ${ERROR}
    fi

    if [[ ! -d "${DIR}/${S_REPOS}" ]]; then
        return ${ERROR}
    fi

    local matched=$(ls ${DIR}/${S_OFA_DELTA} 2> /dev/null | wc -l)
    if [[ "${matched}" == "0" ]]; then
        return ${ERROR}
    fi

    return ${OK}
}

function check_script_location() {
    is_valid_location
    local valid_loc=$?
    if [[ ${valid_loc} -eq ${ERROR} ]]; then
        err "Script was deployed at wrong location! It shall be within IFS package" \
            "folder"
        exit ${LOC_ERROR}
    fi
}

#############################################################################
# Check whether the IFS package is Basic package. If it's basic package ask
# user's confirmation to continue.
# Globals:
#   IS_BASIC
# Arguments:
#   None
# Returns:
#   None
#############################################################################
function check_basic_package() {
    local matched=$(ls ${DIR}/${S_FM} 2> /dev/null | wc -l)
    if [[ $? -ne 0 ]]; then
        err "Couldn't check basic package"
        exit ${RT_ERROR}
    fi
    if [[ "${matched}" == "0" ]]; then
        IS_BASIC=1
        print_msg "Warning: The IFS package is Basic package that doesn’t contain components for"
        print_msg "         management node. The created repo will NOT work for management node."
        while true; do
            read -e -p "Do you want to continue? [y/n] (n): " opt
            log_msg "Do you want to continue? [y/n] (n): ${opt}"
            case ${opt} in
                [Yy]* )
                    break
                    ;;
                "" | [Nn]* )
                    exit ${USR_INT}
                    ;;
            esac
        done
    else
        IS_BASIC=0
    fi
}

#############################################################################
# Fill array KER_VERS with kernel versions we will support in our repo. The
# current implementation fills it with active kernel version. In the future
# we will support user specified versions or fill it with installed kernels.
# Globals:
#   KER_VERS
# Arguments:
#   None
# Returns:
#   None
#############################################################################
function populate_ker_vers() {
    if [[ ${USE_USER_KERS} -eq 0 ]]; then
        # current active kernel
        KER_VERS[0]=$(uname -r)
    fi
}

#############################################################################
# Rebuild kernel rpm for a specified version with 'INSTALL -B' command. Put
# generated kernel rpms in array KER_RPMS
# Globals:
#   KER_RPMS
# Arguments:
#   version release string
# Returns:
#   OK if successes
#   ERROR if fails
#############################################################################
function rebuild_kernel_rpms() {
    local path_pattern
    local exclude_path=""
    local ret
    cd ${DIR}
    if [[ ${USE_CUDA} -eq 1 ]]; then
        path_pattern="*/CUDA/"
        exec_and_log ./${S_INSTALL} -G -B "$1"
        ret=$?
    else
        exclude_path="*/CUDA/*"
        exec_and_log ./${S_INSTALL} -B "$1"
        ret=$?
    fi
    if [[ ${ret} -eq ${OK} ]]; then
        path_pattern+="*kernel*${1//[-]/_}*.rpm"
        # find kernel rpms with matched kernel version.
        KER_RPMS+=($(find ${DIR}/${S_OFA_DELTA}/RPMS -not -path "${exclude_path}" \
                   -path "${path_pattern}"))
    fi
    return ${ret}
}

#############################################################################
# Update symlinks in repos folder to the kernel rpms in array KER_RPMS
# It will remove old symlink and exit if any symlink update fails.
# Globals:
#   REPO_RPM_PATH
# Arguments:
#   None
# Returns:
#   None
#############################################################################
function update_repos_links() {
    REPO_RPM_PATH=${DIR}/${S_REPOS}/
    if [[ ${USE_CUDA} -eq 1 ]]; then
        REPO_RPM_PATH+=${S_REPO_CUDA_RPMS}
    else
        REPO_RPM_PATH+=${S_REPO_COMM_RPMS}
    fi
    # get old kernel rpms links
    cd ${REPO_RPM_PATH}
    local has_error=0
    local old_ker_rpms=($(ls *kernel*.rpm))
    # array of source files. used for recovering links on errors
    local src_old_rpms=()
    for rpm in "${old_ker_rpms[@]}"; do
        src_old_rpms+=($(readlink -f ${rpm}))
        print_msg "Removing link ${rpm}"
        exec_and_log rm -f "${rpm}"
        if [[ ${has_error} -eq 0 && $? -ne ${OK} ]]; then
            has_error=1
        fi
    done
    # create links for new kernel rpms
    for rpm in "${KER_RPMS[@]}"; do
        print_msg "Creating symlink to $rpm"
        exec_and_log ln -s "${rpm}"
        if [[ ${has_error} -eq 0 && $? -ne ${OK} ]]; then
            has_error=1
        fi
    done
    if [[ ${has_error} -eq 1 ]]; then
        err "Failed to update symlinks!"
        # recover changes
        for rpm in "${KER_RPMS[@]}"; do
            rm -f "${rpm##*/}"
        done
        for rpm in "${src_old_rpms[@]}"; do
            ln -s "${rpm}"
        done
        exit ${RT_ERROR}
    fi
}

function check_yum_zypper() {
    which yum > /dev/bull 2>&1
    if [[ $? -eq 0 ]]; then
        USE_YUM=1
    else
        which zypper > /dev/bull 2>&1
        if [[ $? -ne 0 ]]; then
            # shouldn't happen
            err "Couldn't find command 'yum' or 'zypper' in the system!"
            exit ${RT_ERROR}
        fi
    fi
}

function check_createrepo() {
    which createrepo > /dev/bull 2>&1
    if [[ $? -ne 0 ]]; then
        err "Couldn't find command 'createrepo' in the system!"
        exit ${RT_ERROR}
    fi
}

function prepare_repo_info() {
    if [[ ${IS_BASIC} -eq 1 ]]; then
        REPO_ID=${S_BASIC_REPOID}
        REPO_NAME=${S_BASIC_REPONAME}
    else
        REPO_ID=${S_IFS_REPOID}
        REPO_NAME=${S_IFS_REPONAME}
    fi
    if [[ ${USE_CUDA} -eq 1 ]]; then
        REPO_ID+=${S_CUDA_ID_SUFFIX}
        REPO_NAME+=${S_CUDA_NAME_SUFFIX}
    fi
}

#############################################################################
# Check whether repo exists or not for a given repo id. If repo exists, call
# function backup_remove_repo to print out warning message and remove it
# after making a backup copy
# Globals:
#   None
# Arguments:
#   $1 repo id
# Returns:
#   None
#############################################################################
function check_repo() {
    local repoid=$1
    local repo_file
    if [[ ${USE_YUM} -eq 1 ]]; then
        repo_file="$(yum repolist -v ${repoid} 2> /dev/null|grep 'Repo-filename: ')"
        if [[ -n ${repo_file} ]]; then
            repo_file=${repo_file:15}
        fi
    else
        repo_file="$(zypper lr ${repoid} 2> /dev/null|grep 'Repo Info Path : ')"
        if [[ -n ${repo_file} ]]; then
            repo_file=${repo_file:17}
        fi
    fi

    if [[ -n ${repo_file} ]]; then
        print_msg "Found repo ${repoid} at ${repo_file}"
        backup_remove_repo ${repo_file} ${repoid}
    fi
}

#############################################################################
# Backup a repo and then remove it. Will exit on errors.
# Globals:
#   None
# Arguments:
#   $1 repo file path
#   $2 repo id
# Returns:
#   None
#############################################################################
function backup_remove_repo() {
    local repo_file=$1
    local repoid=$2
    local backup_file=$1.backup
    local ignore_backup=0
    print_msg "Warning: repo ${repoid} already exists. Backing up it as ${backup_file}"
    if [[ -e ${backup_file} ]]; then
        print_msg "Warning: File ${backup_file} already exists."
        while true; do
            read -e -p "Do you want to overwrite or ignore? [y/n/i] (y): " opt
            log_msg "Do you want to overwrite or ignore? [y/n/i] (y): ${opt}"
            case ${opt} in
                "" | [Yy]* )
                    break
                    ;;
                [Ii]* )
                    ignore_backup=1
                    break
                    ;;
                [Nn]* )
                    read -e -p "Please provide new file name: " fname
                    log_msg "Please provide new file name: ${fname}"
                    if [[ ! -e ${fname} ]]; then
                        backup_file=${fname}
                        break
                    else
                        print_msg "Warning: File ${fname} already exists."
                    fi
                    ;;
            esac
        done
    fi
    if [[ ${ignore_backup} -eq 0 ]]; then
        print_msg "Backing up ${repo_file} to ${backup_file}"
        exec_and_log cp "${repo_file}" "${backup_file}"
        if [[ $? -ne ${OK} ]]; then
            err "Failed to backup repo ${repoid}!"
            exit ${RT_ERROR}
        fi
    fi
    local rt
    if [[ ${USE_YUM} -eq 1 ]]; then
        exec_and_log rm -f "${repo_file}"
        rt=$?
    else
        exec_and_log zypper rr "${repoid}"
        rt=$?
    fi
    if [[ ${rt} -ne ${OK} ]]; then
        err "Failed to remove existing repo ${repoid}!"
        exit ${RT_ERROR}
    fi
}

function create_yum_repo() {
    local repo_file="/etc/yum.repos.d/${REPO_ID}.repo"
    cat > ${repo_file} << EOF
[${REPO_ID}]
name=${REPO_NAME}
gpgcheck=0
baseurl=file://${REPO_RPM_PATH}
enabled=1
EOF
    if [[ $? -ne 0 ]]; then
        err "Couldn't create repo ${REPO_ID}"
        exit ${RT_ERROR}
    fi
    print_msg
    exec_and_log cat ${repo_file}
    print_msg
}

function create_zypper_repo() {
    exec_and_log zypper ar -G -n "${REPO_NAME}" "${REPO_RPM_PATH}" "${REPO_ID}"
    if [[ $? -ne ${OK} ]]; then
        err "Couldn't create repo ${REPO_ID}"
        exit ${RT_ERROR}
    fi
}

#############################################################################
# For a given folder path, find all rpm files under it and return the
# corresponding unique rpm names. Note, it ignores source rpms.
# Globals:
#   None
# Arguments:
#   $1 folder path
#   $2 file name pattern. If omit, the pattern will be "*.rpm"
# Returns:
#   Print out unique rpm names
#   OK if successes
#   ERROR if fails
#############################################################################
function get_rpm_names() {
    # if we have the same rpm under different versions, such as kernel rpms,
    # we will have duplicate rpm names. So we use associative array here and
    # use rpm name as key to get unique names
    local path=$1
    local pattern="*.rpm"
    if [[ $# -ge 2 ]]; then
        pattern=$2
    fi
    declare -A rpm_names=()
    local name
    local rpms=()
    rpms=($(find "$1" -name "${pattern}"))
    if [[ $? -ne 0 ]]; then
        return ${ERROR}
    fi
    for rpm in "${rpms[@]}"; do
        # skip src rpms
        if [[ "${rpm}" != *".src.rpm" ]]; then
            name="$(rpm --queryformat '%{NAME}' -qp ${rpm})"
            if [[ $? -ne 0 ]]; then
                return ${ERROR}
            fi
            rpm_names[${name}]=1
        fi
    done
    for i in "${!rpm_names[@]}"; do
        echo "${i}"
    done
    return ${OK}
}

#############################################################################
# Collect rpms used only for management node, and then put their names in
# MGT_RPMS. We will use it to figure out the rpms for compute node. Will exit
# on errors.
# Globals:
#   MGT_RPMS
# Arguments:
#   None
# Returns:
#   None
#############################################################################
function get_mgt_pkgs() {
    MGT_RPMS=($(get_rpm_names ${DIR}/${S_FM}/RPMS))
    if [[ $? -ne ${OK} ]]; then
        err "Couldn't collect management required rpms"
        exit ${RT_ERROR}
    fi
    # IntelOPA-Tools-FF includes tools for FF, opamgt and basic tools. We cannot
    # scan the folder and use all the rpms. We have to use prior knowledge here
    MGT_RPMS+=(${MGT_EXT_COM_RPMS[@]})
    if [[ ${USE_YUM} -eq 1 ]]; then
        MGT_RPMS+=(${MGT_EXT_RHEL_RPMS[@]})
    else
        MGT_RPMS+=(${MGT_EXT_SLES_RPMS[@]})
    fi
    log_msg "Management specific packages: ${MGT_RPMS[*]}"
}

#############################################################################
# Collect rpms used only for MPI, and put their names in MPI_RPMS. We will
# use it to figure out the rpms for service node. Will exit on errors.
# Globals:
#   MPI_RPMS
# Arguments:
#   None
# Returns:
#   None
#############################################################################
function get_mpi_pkgs() {
    local mpi_rpms
    mpi_rpms=($(get_rpm_names ${DIR}/${S_MPI}))
    if [[ $? -ne ${OK} ]]; then
        err "Couldn't collect MPI required rpms"
        exit ${RT_ERROR}
    fi
    local sos_rpms
    sos_rpms=($(get_rpm_names ${DIR}/${S_OFA_DELTA} "${S_SOS}*.rpm"))
    if [[ $? -ne ${OK} ]]; then
        err "Couldn't collect Sandia Openshmem required rpms"
        exit ${RT_ERROR}
    fi
    MPI_RPMS=("${mpi_rpms[@]}" "${sos_rpms[@]}" "${S_MPI_SELECTOR}")
    log_msg "MPI specific packages: ${MPI_RPMS[*]}"
}

#############################################################################
# Collect all rpms in our repo, and put their names in ALL_RPMS. Will exit on
# errors.
# Globals:
#   ALL_RPMS
# Arguments:
#   None
# Returns:
#   None
#############################################################################
function get_all_pkgs() {
    ALL_RPMS=($(get_rpm_names ${REPO_RPM_PATH}))
    if [[ $? -ne ${OK} ]]; then
        err "Couldn't collect repo rpms"
        exit ${RT_ERROR}
    fi
}

#############################################################################
# Helper function that removes elements from an array that appear in another
# array. This function applies exact match on element comparison.
# Globals:
#   None
# Arguments:
#   $1 the array to be subtracted. Shall pass in as a string like "a1 a2 ..."
#   $2 the array contains the elements we want to remove. Shall pass in as
#      a string like "b1 b2 ..."
# Returns:
#   the new array string with the result of subtracting the second array from
#   the first array
#############################################################################
function array_subtraction() {
    local src_array=($(echo $1))
    local flt_array=($(echo $2))
    local tmp_array=()
    local keep=0
    for element in "${src_array[@]}"; do
        keep=1
        for filter in "${flt_array[@]}"; do
            if [[ "${element}" == "${filter}" ]]; then
                keep=0
                break
            fi
        done
        if [[ ${keep} -eq 1 ]]; then
            tmp_array+=(${element})
        fi
    done
    echo "${tmp_array[@]}"
}

function display_info() {
    local ifs_ver="$(cd ${DIR};./${S_INSTALL} -V)"
    if [[ $? -ne 0 ]]; then
        err "Couldn't get IFS version"
        exit ${RT_ERROR}
    fi
    echo "Create repo for Intel OPA ${ifs_ver} software"
}

function display_install_command() {
    local yum_zypper
    if [[ ${USE_YUM} -eq 1 ]]; then
        yum_zypper="yum"
    else
        yum_zypper="zypper"
        # rdma-ndd is recommended for SLES. Since no OPA rpm claims dependency
        # on it, we have to explicitly list it.
        ALL_RPMS+=( rdma-ndd )
    fi

    local compute_rpms=()
    print_msg ""
    print_msg "Please use the following recommended commands to install Intel OPA software"
    print_msg ""
    print_msg "Management Node:"
    if [[ ${IS_BASIC} -eq 0 ]]; then
        print_msg "  ${yum_zypper} install ${ALL_RPMS[*]}"
        compute_rpms=($(array_subtraction "${ALL_RPMS[*]}" "${MGT_RPMS[*]}"))
    else
        print_msg "  Not available in basic package"
        compute_rpms=(${ALL_RPMS[@]})
    fi
    print_msg ""
    print_msg "Compute Node:"
    print_msg "  ${yum_zypper} install ${compute_rpms[*]}"

    rpms_to_install=($(array_subtraction "${compute_rpms[*]}" "${MPI_RPMS[*]}"))
    print_msg ""
    print_msg "Services Node:"
    print_msg "  ${yum_zypper} install ${rpms_to_install[*]}"

    rpms_to_install=()
    # remove rpms contains 'kernel' or 'firmware'
    for rpm in "${compute_rpms[@]}"; do
        if [[ "${rpm}" != *"kernel"* && "${rpm}" != *"firmware"* ]]; then
            rpms_to_install+=(${rpm})
        fi
    done
    print_msg ""
    print_msg "Container:"
    print_msg "  ${yum_zypper} install ${rpms_to_install[*]}"
}

function process_help() {
    if [[ "$1" == "--help" ]]; then
        if [[ $# -eq 1 ]]; then
            usage
            exit ${SUCCESS}
        else
            err "Invalid argument."
            usage
            exit ${INV_ARGS}
        fi
    fi
}

function process_info_display() {
    if [[ "$1" == "-i" ]]; then
        if [[ $# -eq 1 ]]; then
            display_info
            exit ${SUCCESS}
        else
            err "Invalid argument."
            usage
            exit ${INV_ARGS}
        fi
    fi
}

function process_arguments() {
    while getopts ":G" opt; do
        case ${opt} in
            G)
                USE_CUDA=1
                ;;
            ?)
                err "Invalid argument."
                usage
                exit ${INV_ARGS}
                ;;
        esac
    done
    shift $((OPTIND - 1))

    # current implementation doesn't support arg value, so we check it
    if [[ $# -gt 0 ]]; then
        err "Invalid argument."
        usage
        exit ${INV_ARGS}
    fi
}

##############################################
# Main function
##############################################
function main() {
    # handle '--help' argument that shouldn't combine with other args, and
    # we handle it before any check
    process_help "$@"

    # check user
    if [[ "$(id -u)" != "0" ]]; then
        err "The script must be run as root"
        exit ${RT_ERROR}
    fi

    # print script start info in log file
    log_script_start "$0 $@"

    # check script location. It shall be within IFS package
    check_script_location

    # check required tools
    check_yum_zypper
    check_createrepo

    # handle '-i' argument that shouldn't combine with other args
    process_info_display "$@"

    # process command arguments
    process_arguments "$@"

    # detect IFS package type and ask user's confirmation to continue for
    # Basic package
    check_basic_package

    # find active kernel version. In the future it will support versions
    # specified by a user or programmatically detected from OS system
    populate_ker_vers

    # check each kernel version and rebuild kernel rpms when need
    print_msg "Checking ${#KER_VERS[@]} kernel version(s)..."
    local error_count=0
    for kernel in ${KER_VERS[@]}; do
        print_msg "Processing kernel ${kernel}..."
        rebuild_kernel_rpms ${kernel}
        if [[ $? -eq ${ERROR} ]]; then
            error_count=$(( error_count + 1 ))
        fi
    done
    # all kernel rpm rebuild fails, exit with RT_ERROR code
    if [[ ${error_count} -eq ${#KER_VERS[@]} ]]; then
        err "Couldn't rebuild kernel rpms."
        exit ${RT_ERROR}
    fi

    # update symlinks in repos folder with new kernel rpms we just built
    update_repos_links

    # update repo database
    print_msg "Updating repo database..."
    exec_and_log createrepo --update "${REPO_RPM_PATH}"
    if [[ $? -ne ${OK} ]]; then
        err "Couldn't update repo data ${REPO_RPM_PATH}"
        exit ${RT_ERROR}
    fi

    # get repo related info, i.e. repo id and name
    prepare_repo_info

    # backup and remove any possible existing OPA repos
    check_repo "${S_IFS_REPOID}"
    check_repo "${S_IFS_REPOID}${S_CUDA_ID_SUFFIX}"
    check_repo "${S_BASIC_REPOID}"
    check_repo "${S_BASIC_REPOID}${S_CUDA_ID_SUFFIX}"

    # create repo
    print_msg "Creating repo ${REPO_ID}"
    if [[ ${USE_YUM} -eq 1 ]]; then
        create_yum_repo
    else
        create_zypper_repo
    fi
    print_msg "Repo ${REPO_ID} was successfully created."

    get_all_pkgs
    if [[ ${IS_BASIC} -eq 0 ]]; then
        get_mgt_pkgs
    fi
    get_mpi_pkgs

    display_install_command
}

trap "exit ${USR_INT}" SIGHUP SIGTERM SIGINT
main "$@"