#!/bin/bash
#
# Copyright (C) 2023 MOXA Inc. All rights reserved.
# This software is distributed under the terms of the MOXA SOFTWARE NOTICE.
# See the file LICENSE for details.
#
# Authors:
#       2023  Wilson YS Huang  <wilsonys.huang@moxa.com>

source "${INSTL_SCRIPT_DIR}/lib/util.sh"
source "${INSTL_SCRIPT_DIR}/lib/logger.sh"
log::init "${INSTL_LOG_FILE}" "${INSTL_LOG_LEVEL}"

set -e

REPO_NAME="moxa-scaler-utils"
SRC_PATH_PREFIX="${INSTL_TOP_DIR}/src/${REPO_NAME}"

main() {
        local src_tag
        local src_ver
        src_tag="$1"
        src_ver="$2"

        log::info "Installing ${REPO_NAME} (${src_ver})"

        {
                case "${OS_PACKAGE_MANAGER}" in
                "apt")
                        apt-get update
                        apt-get install libjson-c-dev -y
                        ;;
                "yum")
                        # json-c-devel package is in codeready-builder-for-rhel-9-x86_64-rpms repository
                        if ! subscription-manager repos --list-enabled | grep -q "codeready-builder-for-rhel-9-x86_64-rpms"; then
                                subscription-manager repos --enable "codeready-builder-for-rhel-9-x86_64-rpms" >/dev/null 2>&1
                        fi

                        yum makecache
                        yum install json-c-devel -y
                        ;;
                esac

                pushd "${SRC_PATH_PREFIX}-${src_tag}" >/dev/null

                make clean
                make
                make install
                cp mx-scalerd.service /lib/systemd/system/
                systemctl enable mx-scalerd.service
                systemctl start mx-scalerd.service

                popd
        } >>"${INSTL_LOG_FILE}" 2>&1
}

main "$@"
