#!/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  Elvis Yao  <ElvisCW.Yao@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="libgpiod"
SRC_PATH_PREFIX="${INSTL_TOP_DIR}/src/${REPO_NAME}"

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

        if ! /sbin/ldconfig -p | grep -q "libgpiod"; then

                log::debug "OS_PACKAGE_MANAGER=${OS_PACKAGE_MANAGER}"

                {
                        case "${OS_PACKAGE_MANAGER}" in
                        "apt")
                                apt-get update
                                apt-get install autoconf \
                                        autoconf-archive libtool \
                                        pkg-config -y
                                ;;
                        "yum")
                                yum makecache
                                yum install autoconf \
                                        autoconf-archive libtool \
                                        pkg-config -y
                                ;;
                        esac
                } >>"${INSTL_LOG_FILE}" 2>&1
        fi

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

        {
                pushd "${SRC_PATH_PREFIX}-${src_tag}" >/dev/null
                ./autogen.sh --enable-tools=yes
                make -j"$(nproc)"
                make install
                ldconfig /usr/local/lib/
                popd
        } >>"${INSTL_LOG_FILE}" 2>&1
}

main "$@"
