#!/usr/bin/bash

# author: Vasiliy Kleschov <vkleschov@cloudlinux.com>
# created: 2018-03-14
# CloudLinux IP registration tool

# This wrapper runs as root. External commands are invoked by absolute path
# (e.g. /usr/sbin/rhn_check, /usr/bin/tee) so neither the caller's PATH nor an
# inherited shell function of the same name can hijack them: a command word
# containing '/' bypasses function lookup and PATH entirely. The fixed, trusted
# PATH below is kept as defense-in-depth for any remaining bare lookups, and we
# drop inherited functions for the commands we run.
PATH=/usr/sbin:/usr/bin:/sbin:/bin
export PATH
unset -f rhn_check tee 2>/dev/null

SKIP_RHNCHECK=0
SHOW_HELP=0
USE_STDIN_KEY=0
SYSTEMID_FILE="/etc/sysconfig/rhn/systemid"
LOG_FILE="/var/log/up2date"
# How to register again when this script declines to. Name clnreg_ks for both
# license types: it forwards --activationkey=- so rhnreg_ks reads the key from
# stdin as one line (no prompt is shown), so the key never lands in argv or
# shell history (CLOS-4594).
RENEW_HINT="/usr/sbin/clnreg_ks --force (IP-based license), or /usr/sbin/clnreg_ks --activationkey=- --force and type the activation key on the next line (activation key)."

# simple cycle that does not meant to do
# some completed stuff like positional arguments
# if you need something more -> rewrite this script in python
for opt in "$@"
do
    case "$opt" in
        --force) SKIP_RHNCHECK=1
            ;;
        --help|-h) SHOW_HELP=1
            ;;
        # '-' is the stdin sentinel (CLOS-4594/F-50): the key is piped in, not on
        # argv. Callers using it should also pass --force so the pre-flight
        # rhn_check below is skipped and does not consume the piped key. This case
        # must precede the generic --activationkey=* case below.
        --activationkey=-) USE_STDIN_KEY=1
            ;;
        --activationkey=*|--activationkey)
            ;;
        --edition=*|--edition)
            ;;
    esac
done

# we should show help even if license exists
if [[ ${SHOW_HELP} == 1 ]]; then
    /usr/sbin/rhnreg_ks --help
    exit $?
fi;

# the meaning of the following checks is:
# 1. to run ip registration on first yum-rhn-plugin
#    activation (probably right after vm boot)
# 2. to fix ip license if some template contains
#    systemid file for no reason (that is error 9 from CLN)
# but don't change license if cln is just down

# if systemid does not exist it means we don't have
# license yet and not reason to call rhn_check (it will fail anyway)
if [[ -f "${SYSTEMID_FILE}" ]]; then
  # skip rhn_check only with --force option passed
  if [[ ${SKIP_RHNCHECK} == 0 ]]; then
      result=$(/usr/sbin/rhn_check 2>&1)
      rc=$?
      if [[ "${rc}" = "0" ]]; then
          # rhn_check also exits with zero while another rhn_check holds its
          # lock or while RHN is disabled. Leave the registration alone
          # (RHNCLT-10): a forced re-registration may drop the server's stats
          # in CM (LU-2317), and an IP-based one may take the license from
          # other servers behind the same NAT or drop their registrations
          # (AL-2325, PF-2910). Show what rhn_check printed: RHN disabled or a
          # malformed server URL is fixed in the configuration, not by renewal.
          if [[ -n "${result}" ]]; then
              printf '%s\n' "${result}"
          fi
          echo "rhn_check exited with code zero, so the registration was left unchanged." \
               "If cldetect --check-license or package updates report a CLN registration problem, renew it as root: ${RENEW_HINT}"
          exit 0
      elif [[ "${result}" =~ "Invalid System Credentials" ]]; then
          # we get and error meaning that systemid of server is
          # no longer valid for server-side application
          # in this case we can try obtaining new license
          echo "${result}" >> "${LOG_FILE}"
          echo "Seems like server is missing license. Trying to get new one using IP licensing flow." | /usr/bin/tee -a "${LOG_FILE}"
      else
          # rhn_check also fails when CLN is down or on network errors
          # (LU-2317); a forced renewal fixes neither, so ask to fix the error
          # first.
          if [[ -z "${result}" ]]; then  # e.g. killed: there is no error above
              result="rhn_check exited with code ${rc} and printed nothing."
          fi
          printf '%s\n' "${result}" | /usr/bin/tee -a "${LOG_FILE}"
          echo "Unable to check license status and register server." \
               "Fix the error above and run clnreg_ks again; if it keeps failing, renew as root: ${RENEW_HINT}"
          exit $rc
      fi;
  fi;
elif [[ ${USE_STDIN_KEY} == 1 ]]; then
  echo "Server does not have active license yet. Reading the activation key from standard input."
else
  echo "Server does not have active license yet. Trying to get one using IP licensing flow."
fi

if [[ ${USE_STDIN_KEY} == 1 ]]; then
    # The caller passes the activation key on stdin (kept off the command line).
    # Forward --activationkey=- (already in "$@") to rhnreg_ks and let it read
    # stdin. Do NOT inject the IPL default key, which would be a second
    # --activationkey.
    /usr/sbin/rhnreg_ks --force $@
else
    /usr/sbin/rhnreg_ks --activationkey=IPL --force $@
fi
ret=$?

exit $ret