apiVersion: v1
kind: ConfigMap
metadata:
  name: entitlement-tester-entrypoint
  namespace: default
data:
  entrypoint.sh: |-
    #!/bin/bash
    set -o errexit;
    set -o pipefail;
    set -x
    env
    echo "# Kernel version"
    uname -a

    echo
    echo "# Host OS Release"
    cat /etc-host/os-release
    source /etc-host/os-release

    if [[ "${REMOVE_HOST_ENTITLEMENT:-}" == "1" ]]; then
       # this flag is activated in 'entitlement_test_in_cluster',
       # so that we can test the given PEM key without risking that
       # the host / cluster-wide entitlement alters the test result.
       # This is harmless for the host of course.

       echo "# INFO: removing host entitlement links (REMOVE_HOST_ENTITLEMENT=${REMOVE_HOST_ENTITLEMENT})"
       rm -fv /etc/pki/entitlement-host /etc/rhsm-host

       echo
       echo "# md5sum of pod entitlement files (debug)"
       if md5sum /etc/rhsm/rhsm.conf /etc/pki/entitlement/entitlement{,-key}.pem; then
         echo "# INFO: pod entitlement files found"
      else
        echo "#"
        echo "# INFO: pod entitlement files missing"
        echo "#"
      fi

    else
      echo
      echo "# md5sum of host entitlement files (debug)"
      if md5sum /etc/rhsm-host/rhsm.conf /etc/pki/entitlement-host/entitlement{,-key}.pem; then
        echo "# INFO: host entitlement files found"
      else
        echo "#"
        echo "# WARNING: host entitlement files missing"
        echo "#"
      fi
    fi

    echo "# INFO: Storing ${RHEL_VERSION} into /etc/yum/vars/releasever"
    echo "${RHEL_VERSION}" > /etc/yum/vars/releasever

    echo
    echo "# test EUS and OCP repositories (debug)"

    for repo in rhocp-${OPENSHIFT_VERSION}-for-rhel-8-x86_64-rpms rhel-8-for-x86_64-baseos-eus-rpms; do
      if dnf config-manager --set-enabled $repo; then
        if dnf makecache; then
          echo "# INFO: repo '$repo' enabled"
        else
          echo "#"
          echo "# WARNING: failed to cache repo '$repo'"
          echo "#"
          dnf config-manager --set-disabled $repo
        fi

      else
        echo "#"
        echo "# WARNING: failed to enable repo '$repo'"
        echo "#"
      fi
    done

    if [ -f /etc/pki/entitlement-host/entitlement.pem ]; then
      # inspect the PEM certificate "notAfter" date
      yum install -yq openssl

      EXPIRATION_WARNING_DELAY_HR=48
      openssl x509 -enddate -noout -in /etc/pki/entitlement-host/entitlement.pem # prints the `notAfter` date
      if ! openssl x509 -checkend $(($EXPIRATION_WARNING_DELAY_HR * 60 * 60)) -noout -in /etc/pki/entitlement-host/entitlement.pem; then
        echo "WARNING: PEM certificate expires in less than ${EXPIRATION_WARNING_DELAY_HR} hours ..."
      fi
    else
      echo "Entitlement file not found, cannot check its expiration date."
    fi

    echo
    echo "# ensure that RH repositories can be accessed"

    dnf list kernel-core --showduplicates
    # done
