#!/usr/bin/env bash
set -e
#set -x

LOCAL_IMAGE=sslproxy
TAG=2.2.${BUILD_NUMBER:-dev}
REMOTE_IMAGE=dkregistry.xai-corp.net:5000/${LOCAL_IMAGE}:${TAG}

LOG=$(mktemp)

export LOCAL_IMAGE
export REMOTE_IMAGE
export TAG

dc() {
    # shellcheck disable=SC2068
    docker-compose \
    -f docker-compose.yml \
    -f docker-compose.build.yml \
    $@
}

###
build() {
  dc build
}

build_test() {
  echo -e "\e[33mtesting the image\e[39m"

  dc up -d --force-recreate
  docker ps | grep sslproxy

  sleep 5
  assertTeapot https abcapi.xai-corp.net
  assertTeapot https dkui.xai-corp.net
  assertTeapot https git.xai-corp.net
  assertTeapot https jenkins.xai-corp.net
  assertTeapot https xaibox.xai-corp.net
  assertMisdirectedRequest https not.xai-corp.net

  #cert renewal
  assertTeapot http xai-corp.net
  assertTeapot http abcapi.xai-corp.net
  assertTeapot http dkui.xai-corp.net
  assertTeapot http git.xai-corp.net
  assertTeapot http jenkins.xai-corp.net
  assertTeapot http xaibox.xai-corp.net
  assertTeapot http metrics.xai-corp.net
}

function assertMisdirectedRequest() {
  proto=$1
  domain=$2
  set -e
  echo -e "\033[94m${proto}://${domain}\033[39m testing for mistrected request"
  curl -IskH "Host: ${domain}" "${proto}://localhost" | tee "$LOG" | grep "421 Misdirected Request"
}

function assertBadGateway() {
  proto=$1
  domain=$2
  set -e
  echo -e "\033[94m${proto}://${domain}\033[39m"
  curl -IskH "Host: ${domain}" "${proto}://localhost" | tee "$LOG" | grep "502 Bad Gateway"
}


function assertTeapot() {
  proto=$1
  domain=$2
  set -e
  echo -e "\033[94m${proto}://${domain}\033[39m"
  curl -IskH "Host: ${domain}" "${proto}://localhost" | tee "$LOG" | grep "418"
}

build_save() {
  echo push to registry

  docker tag "$LOCAL_IMAGE:$TAG" "$REMOTE_IMAGE"
  docker push "$REMOTE_IMAGE"
}

function trap_exit() {
  code=$?
  dc down
  if [ $code -gt 0 ]; then
    echo
    cat "$LOG"
    rm "$LOG"
    dc logs --tail=10
    echo -e "\033[31mFailed to build functional image\033[39m"
    exit $code
  fi

  rm "$LOG"
  echo -e "\033[32mSuccess:\033[39m ${LOCAL_IMAGE}:${TAG} successfully built"
}
trap  trap_exit EXIT

print_usage() {
  printf "Usage: %s: [-b] [-t] [-s] \n" "$0"
  echo -b build
  echo -t test
  echo -s push to registry
  echo -h help
  exit 0
}

######
if [ -z "$1" ]; then
  build && build_test && build_save
  exit
fi

while getopts btdhs name
do
    case $name in
    b)    build;;
    t)    build_test;;
    s)    build_save;;
    *)    print_usage;;
    esac
done
