#!/bin/bash

DEPLOY_DIR=deploy
QUAY_USER=pietro
SSH_KEY=/home/${QUAY_USER}/.ssh/id_rsa
QUAY_HOSTNAME=localhost
PORT=8443
ALT_NAME="DNS:${QUAY_HOSTNAME},DNS:example.com,DNS:www.example.net,IP:10.0.0.1"
CERT=cert.pem
KEY=key.pem

function ceckCerts(){
  CERT_SHA=$(openssl x509 -in "$CERT" -noout | sha256sum | cut -d \  -f1)
  QUAY_SHA=$(echo | openssl s_client -connect ${1}:${PORT} -showcerts 2>/dev/null | openssl x509 -noout | sha256sum | cut -d \  -f1)
  if [ "$CERT_SHA" == "$QUAY_SHA" ]; then
	  echo OK: QUAY_SHA: $QUAY_SHA CERT_SHA: $CERT_SHA
  else
	  echo KO: QUAY_SHA: $QUAY_SHA CERT_SHA: $CERT_SHA
  fi
}

function createCert(){
  sudo openssl req -x509 -newkey rsa:4096 -sha256 -days 3650 -nodes \
    -keyout "$KEY" -out "$CERT" -subj "/CN=${QUAY_HOSTNAME}" \
    -addext "subjectAltName=${ALT_NAME}"
}

function clean(){
  sudo rm -rf $DEPLOY_DIR
}

function extractQuay(){
  make build-online-zip
  tar xzvf openshift-mirror-registry.tar.gz -C $DEPLOY_DIR
  rm -f ${DEPLOY_DIR}/README.md
}

function installQuay(){
  sudo ./openshift-mirror-registry install --sslCert "$CERT" --sslKey "$KEY"  --quayHostname ${QUAY_HOSTNAME}:${PORT} -k "$SSH_KEY" -u $QUAY_USER 
} 

function installQuayInvalid(){
  # this should fail because the certificate hostname does not match with --quayHostname
  sudo ./openshift-mirror-registry install --sslCert "$CERT" --sslKey "$KEY"  --quayHostname 127.0.0.1:${PORT} -k "$SSH_KEY" -u $QUAY_USER
  if [ "$?" == "0" ]; then
	  echo "ERROR: cert hostname verification failed"
  fi
}

function installQuayInvalidSkipCheck(){
  # this should not fail because the cert chek is skipped
  sudo ./openshift-mirror-registry install --sslCert "$CERT" --sslKey "$KEY"  --quayHostname 127.0.0.1:${PORT} --sslCheckSkip -k "$SSH_KEY" -u $QUAY_USER
}

function uninstall(){
  sudo ./openshift-mirror-registry uninstall -k "$SSH_KEY" -u $QUAY_USER -vvv
}

function msg(){
  echo '#################################################'
  echo "MSG: $@"
  echo '#################################################'
}

clean
mkdir -p "$DEPLOY_DIR"
extractQuay
cd "$DEPLOY_DIR"

msg "Create the certificate with '${ALT_NAME}' name"
createCert

msg "Install Quay "
installQuay

msg "Check that the certificate on ${QUAY_HOSTNAME}:${PORT} is the same of $CERT"
ceckCerts $QUAY_HOSTNAME

msg "Install Quay with --quayHostname 127.0.0.1:${PORT} (should fail)"
installQuayInvalid

msg "Remove Quay"
uninstall

msg "Install Quay with --quayHostname 127.0.0.1:${PORT} and --sslCheckSkip (should pass the install but quay-app will not start)"
installQuayInvalidSkipCheck
