#!/bin/bash

# h683.eulerosv2r8
# h860.eulerosv2r10
function get_os_ver()
{
	uname -r | awk -F. '{print $(NF-2)"."$(NF-1)}'
}

# 801sph608 -> klp_FixIrqLost-4.19.36-vhulk1907.1.0.h683.eulerosv2r8.aarch64-1.0-1.aarch64.rpm
# 812sph103 -> klp_FixIrqLost-4.19.90-vhulk2110.1.0.h860.eulerosv2r10-1.0-1.aarch64.rpm
function get_pkg_name()
{
	os_name=$1
	pkg_path=$2

	if [ ! -d "$pkg_path" ]; then
		echo ""
		return	
	fi

	pkg_num=`ls $pkg_path | grep "$os_name" | wc -l`
	if [ $pkg_num != 1 ]; then
		echo ""
		return
	fi

	pkg_name=`ls $pkg_path | grep $os_name`
	echo $pkg_path/$pkg_name
}

function check_pkg_install()
{
	pkg_keyword="klp_FixIrqLost"
	rpm -qa | grep $pkg_keyword
}

function install_step()
{
	install_name=`check_pkg_install`
	if [ -n "$install_name" ]; then
		return 0
	fi

	tgz_name="klp_patch_pkgs.tgz"
    dir_path=`cd $(dirname $0); pwd`
    if [ ! -f $dir_path/$tgz_name ]; then
    	echo "Not found pkgs with tool"
    	return 1
    fi

    cd $dir_path
    tar -zxf $tgz_name
    pkg_name=`get_pkg_name $(get_os_ver) ${dir_path}`
    if [ -z "$pkg_name" ]; then
    	echo "Not found pkg for current os"
    	return 2
    fi

    rpm -Uvh $pkg_name
    install_name=`check_pkg_install`
    if [ -z "$install_name" ]; then
    	echo "Install pkg failed"
    	return 3
    fi
    return 0
}

function uninstall_step()
{
	install_name=`check_pkg_install`
	if [ -z "$install_name" ]; then
		return 0
	fi

	rpm -e $install_name
	install_name=`check_pkg_install`
	if [ -n "$install_name" ]; then
		echo "Uninstall pkg failed"
		return 1
	fi
	return 0
}

function usage()
{
    echo "usage: $0 [install|uninstall]"
    return -1
}

function main()
{
	opt_cmd=$1
	ret=0
	case "$opt_cmd" in
		"install")
			install_step
			ret=$?
		;;
		"uninstall")
			uninstall_step
			ret=$?
		;;
		*)
			usage
			ret=$?
		;;
	esac
    exit $ret
}


main "$@" 2>&1
