#!/bin/sh -x
# vim:tw=0:et:sw=4:ts=4

#echo "the repository bootstrap is down for maintainance. Please check back in 1 hour."
#[ -n "$DEBUG" ] || exit 1

# The purpose of this script is to set up the Dell yum repositories on your 
# system. This script will also install the Dell GPG keys used to sign 
# Dell RPMS.

# these two variables are replaced by the perl script 
# with the actual server name and directory.
SERVER="https://linux.dell.com"
# mind the trailing slash here...
REPO_URL="/repo/hardware/ism/"
REPO_NAME="dell-ism-update"
GPG_KEY_REPO="/repo/pgp_pubkeys/"
# these are 'eval'-ed to do var replacement later.
GPG_KEY_LOCATION=${SERVER}${GPG_KEY_REPO}
#DSU_INSTALL_PATH='/usr/libexec/dell_dup/'

GPG_KEY_NAME[${#GPG_KEY_NAME[*]}]='0x756ba70b1019ced6.asc'
GPG_KEY_NAME[${#GPG_KEY_NAME[*]}]='0x1285491434D8786F.asc'
GPG_KEY_NAME[${#GPG_KEY_NAME[*]}]='0xca77951d23b66a9d.asc'
GPG_KEY_NAME[${#GPG_KEY_NAME[*]}]='0x3CA66B4946770C59.asc'

GPG_KEY_ID[${#GPG_KEY_ID[*]}]='1019CED6'
GPG_KEY_ID[${#GPG_KEY_ID[*]}]='34D8786F'
GPG_KEY_ID[${#GPG_KEY_ID[*]}]='23B66A9D'
GPG_KEY_ID[${#GPG_KEY_ID[*]}]='46770C59'

IMPORT_GPG_CONFIRMATION="na"

##############################################################################
#  Should not need to edit anything below this point
##############################################################################

set -e
[ -z "$DEBUG" ] || set -x

get_dist_version(){
    local REL_RPM rpmq
    # let user override... unwise but necessary for testing
    ([ -z "$dist_base" ] && [ -z "$dist_ver" ] && [ -z "$dist" ]) || return 0
    dist_base=unknown
    dist_ver=
    rpmq='rpm --qf %{name}-%{version}-%{release}\n -q'
    if $rpmq --whatprovides redhat-release >/dev/null 2>&1; then
        REL_RPM=$($rpmq --whatprovides redhat-release 2>/dev/null | tail -n1)
        VER=$(rpm -q --qf "%{version}\n" $REL_RPM)
        REDHAT_RELEASE=$VER

        # RedHat: format is 3AS, 4AS, 5Desktop... strip off al alpha chars
        # Centos/SL: format is 4.1, 5.1, 5.2, ... strip off .X chars
        dist_base=el
        dist_ver=${VER%%[.a-zA-Z]*}

        if echo $REL_RPM | grep -q centos-release; then
            CENTOS_RELEASE=$VER
        fi

    elif $rpmq --whatprovides distribution-release >/dev/null 2>&1; then
        REL_RPM=$($rpmq --whatprovides distribution-release 2>/dev/null | tail -n1)
        lowercase_name=$(echo $REL_RPM | tr '[:upper:]' '[:lower:]')
        case $lowercase_name in
            sles*|suse*)
                SUSE_RELEASE=$(rpm -q --qf "%{version}\n" $REL_RPM)
                dist_base=suse
                dist_ver=${SUSE_RELEASE%%[.a-zA-Z]*}
        esac
    fi

    dist=$dist_base$dist_ver
}

get_user_confirmation() {
	read -p "Do you want to import Dell GPG keys (y/n)?" yn
	case $yn in
		[Yy]* ) IMPORT_GPG_CONFIRMATION="yes";;
		[Nn]* ) IMPORT_GPG_CONFIRMATION="no"; echo "Continuing without importing keys";;
		* ) IMPORT_GPG_CONFIRMATION="no";  echo "Incorrect option. Continuing without importing keys";;
	esac
}

install_gpg_key() {
    eval GPG_KEY_URL=${GPG_KEY_LOCATION}$1
    GPG_FN=$(mktemp /tmp/GPG-KEY-$$-XXXXXX)
    trap "rm -f $GPG_FN" EXIT HUP QUIT TERM
    curl -s -o ${GPG_FN} ${GPG_KEY_URL}
    email=$(gpg -v ${GPG_FN} 2>/dev/null | grep -i @dell.com | sed 's/.*<\(.*\)>.*/\1/')
	
	set +e
	rpm -qa | grep gpg-pubkey | grep ${2,,} 2>/dev/null 1>/dev/null
	if [ $? -ne 0 ]; then
		if [ "${IMPORT_GPG_CONFIRMATION}" = "na" ]; then
			get_user_confirmation
		fi
		if [ "${IMPORT_GPG_CONFIRMATION}" = "yes" ]; then
			echo "    $1: Importing key into RPM."
			rpm --import ${GPG_FN} 2>/dev/null 1>/dev/null
			if [ $? -ne 0 ]; then
				echo "GPG-KEY import failed."
				echo "   Downloading the key failed or insufficient permissions to import the key."
				rm -f $GPG_FN
				exit 1
			fi
		else
			set -e
			rm -f $GPG_FN
			trap - EXIT HUP QUIT TERM
			return
		fi
	else
		echo "    $1: Key already exists in RPM, skipping"
	fi
	
	
	gpg --list-keys $2 2>/dev/null 1>/dev/null
	if [ $? -ne 0 ]; then
		if [ "${IMPORT_GPG_CONFIRMATION}" = "na" ]; then
			get_user_confirmation
		fi
		if [ "${IMPORT_GPG_CONFIRMATION}" = "yes" ]; then
			echo "                            Importing key into GPG."
			gpg --import ${GPG_FN} 2>/dev/null 1>/dev/null
			if [ $? -ne 0 ]; then
				echo "GPG-KEY import failed."
				echo "   Downloading the key failed or insufficient permissions to import the key."
				rm -f $GPG_FN
				exit 1
			fi
		fi
	else
		echo "                            Key already exists in GPG, skipping"
	fi
	
	
	set -e
    rm -f $GPG_FN
    trap - EXIT HUP QUIT TERM
}


write_repo() {
    cat > $1 <<-EOF
		[${REPO_NAME}]
		name=iDRAC Service Module
		baseurl=${SERVER}${REPO_URL}os_dependent/${OS_TYPE}/${OS_RELEASE}
		gpgcheck=0
		gpgkey=${GPG_KEY_LOCATION}${GPG_KEY_NAME[0]}
		       ${GPG_KEY_LOCATION}${GPG_KEY_NAME[1]}
		       ${GPG_KEY_LOCATION}${GPG_KEY_NAME[2]}
               ${GPG_KEY_LOCATION}${GPG_KEY_NAME[3]} 
		enabled=1	
EOF
}

install_all_gpg_keys() {
	echo "Checking for Dell GPG keys..."
    local i=0
    while [ $i -lt ${#GPG_KEY_NAME[*]} ]; do
		if [ "${IMPORT_GPG_CONFIRMATION}" = "no" ]; then
			return
		fi
		
		# Skip keys that fail on RHEL 10
		if [ "$dist" = "el10" ]; then
			if [ "${GPG_KEY_ID[$i]}" = "1019CED6" ]; then
				echo "    ${GPG_KEY_NAME[$i]}: Skipping on RHEL 10 (Policy rejected asymmetric algorithm)"
				i=$(( $i + 1 ))
				continue
			fi
			if [ "${GPG_KEY_ID[$i]}" = "23B66A9D" ]; then
				echo "    ${GPG_KEY_NAME[$i]}: Skipping on RHEL 10 (Policy rejected asymmetric algorithm)"
				i=$(( $i + 1 ))
				continue
			fi
		fi
		
        install_gpg_key ${GPG_KEY_NAME[$i]} ${GPG_KEY_ID[$i]}
        i=$(( $i + 1 ))
    done
}


# sets $dist
get_dist_version

if [ "${dist}" = "unknown" ]; then
    echo "Unable to determine that you are running an OS I know about."
    echo "Handled OSs include Red Hat Enterprise Linux and CentOS,"
    exit 1
fi

install_all_gpg_keys

case $dist in
    el7*|el8*|el9*|el10*)
    	if [ "$dist" == "el8" ]; then
		OS_RELEASE=RHEL8_64
                OS_TYPE=redhat
    	elif [ "$dist" == "el9" ]; then
		OS_RELEASE=RHEL9_64
                OS_TYPE=redhat
	elif [ "$dist" == "el10" ]; then
		OS_RELEASE=RHEL10_64
                OS_TYPE=redhat
	else
    		echo "Unable to determine that you are running an unsupported OS."
    		echo "Handled OSs include Red Hat Enterprise Linux 8.x and 7.x,"
    		exit 1
	fi
        echo "Write repository configuration"
        mkdir -p /etc/yum.repos.d ||:
        write_repo /etc/yum.repos.d/$REPO_NAME.repo
        ;;
      suse[12-15]*)
	if [ "$dist" == "suse15" ]; then
		OS_RELEASE=SLES15_64
                OS_TYPE=suse
	elif [ "$dist" == "suse16" ]; then
		OS_RELEASE=SLES16_64
                OS_TYPE=suse
	fi
	echo "Write repository configuration"
	mkdir -p /etc/zypp.repos.d ||:
	write_repo /etc/zypp/repos.d/$REPO_NAME.repo
	;;
esac

echo "Done!"
exit 0
