#!/bin/bash
#
# KernelCare (https://kernelcare.com/) installation script
# Copyright (c) 2017 CloudLinux Inc. All Rights Reserved

set -e -o pipefail

DRY_RUN=
while getopts n option
do
case "${option}"
in
n) DRY_RUN=1;;
esac
done

# Default repo could be redefined during installation
repo=${KCARE_REPO:-"https://repo.cloudlinux.com"}/kernelcare
name="kernelcare-latest"

# Tune debian repo
if [ -e /etc/debian_version ]; then
	repo=${repo}-debian
fi

# Get curl
if hash apt-get 2>/dev/null; then
    apt-get -y -q install curl > /dev/null
fi
if hash yum 2>/dev/null; then
    yum -y -q install curl > /dev/null
fi

if [ -e /etc/os-release ]; then
	rel=$(grep -w 'VERSION_ID' /etc/os-release | cut -d'.' -f1 | grep -oE "[0-9]*" || :)
	distr=$(grep -w 'ID' /etc/os-release | cut -d'=' -f2|tr -d '"' | xargs || :)
	distr_like=$(grep -w 'ID_LIKE' /etc/os-release | cut -d'=' -f2|tr -d '"' || :)

	case $distr in
		"debian")
			if [ "$rel" -ge "10" ]; then pkg=${name}-10.deb
			elif [ "$rel" -eq "9" ]; then pkg=${name}-9.deb
			elif [ "$rel" -eq "8" ]; then pkg=${name}-8.deb
			else pkg=${name}-6.deb
			fi
		;;
		"ubuntu")
			pkg=${name}-8.deb
		;;
		"amzn")
			# TODO: Remove this hack after amzn1 support dropped
			[[ "${distr}" -eq "amzn" ]] && [[ "${rel}" -eq "2018" ]] && yum install -y python-argparse
			pkg=${name}-7.rpm
		;;
		"centos")
			pkg=${name}-${rel}.rpm
		;;
		"rhel")
			pkg=${name}-${rel}.rpm
		;;
		"ol")
			pkg=${name}-${rel}.rpm
		;;
		"cloudlinux")
			pkg=${name}-${rel}.rpm
		;;
		"virtuozzo")
			pkg=${name}-${rel}.rpm
		;;
		* )
            echo "WARNING: Sorry, this distro isn't supported yet. If you'd like it to be, let us know at feedback@cloudlinux.com."
            case $distr_like in
                *"ubuntu"*)
                    if [ "$rel" -ge "9" ]; then pkg=${name}-9.deb
                    elif [ "$rel" -eq "8" ]; then pkg=${name}-8.deb
                    else pkg=${name}-6.deb
                    fi
                ;;
                * )
			        rel='7'
			        pkg=${name}-${rel}.rpm
                ;;
            esac
		;;
	esac
elif [ -e /etc/system-release ]; then
	rel=$(cut -d'.' -f1 /etc/system-release | grep -oE "[0-9]")
	pkg=${name}-${rel}.rpm
else
	rel=$(cut -d'.' -f1 /etc/redhat-release | grep -oE "[0-9]")
	pkg=${name}-${rel}.rpm
fi


cd /root/

URL="${repo}/${pkg}"

echo "${URL}"
if [ -n "${DRY_RUN}" ]; then
    exit 0
fi

curl -O "${URL}"

if hash apt-get 2>/dev/null; then
    dpkg --force-confmiss --force-depends -i ./$pkg && apt-get --fix-broken -o Dpkg::Options::="--force-confmiss" --yes install
elif hash yum 2>/dev/null; then
    rpm --import ${repo}/RPM-GPG-KEY-KernelCare
    if [ "$rel" == "5" ]; then
        yum -y localinstall $pkg --nogpgcheck
    else
	    yum -y localinstall $pkg
    fi
else
    echo "Unable to install kernelcare: this linux distribution is not yum/dpkg enabled."
fi
