#!/bin/bash
#
# Copyright (C) 2024 MOXA Inc. All rights reserved.
# This software is distributed under the terms of the MOXA SOFTWARE NOTICE.
# See the file LICENSE for details.
#
# Authors:
#       2024  Henry LC Chen  <henrylc.chen@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="intel-gpu-i915-backports"
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})"

        log::info " Installing dependencies"

        {
                case "${OS_PACKAGE_MANAGER}" in
                "apt")
                        apt-get update
                        apt-get install dkms make debhelper devscripts build-essential flex bison mawk -y
                        ;;
                "yum")
                        yum makecache
                        yum install dkms make debhelper devscripts build-essential flex bison mawk -y
                        ;;
                esac
        } >>"${INSTL_LOG_FILE}" 2>&1

        log::info " Build package & install"
        {
                pushd "${SRC_PATH_PREFIX}-${src_tag}" >/dev/null

                case "${OS_PACKAGE_MANAGER}" in
                "apt")
                        if [ -f "version" ]; then
                                local i915_moxa_ver
                                i915_moxa_ver=$(cat version)
                                make i915dkmsdeb-pkg BUILD_VERSION="$i915_moxa_ver"
                        else
                                make i915dkmsdeb-pkg
                        fi
                        dpkg -i ../intel-i915*.deb
                        ;;
                "yum")
                        if [ -f "version" ]; then
                                local i915_moxa_ver
                                i915_moxa_ver=$(cat version)
                                make i915dkmsrpm-pkg BUILD_VERSION="$i915_moxa_ver"
                        else
                                make i915dkmsrpm-pkg
                        fi
                        rpm -ivh ../intel-i915*.rpm
                        ;;
                esac

                rm -f ../intel-i915*

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

main "$@"
