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

LETSENCRYPT_IMAGE=dkregistry.xai-corp.net:5000/xaicorp/acme-certbot
LETSENCRYPT_MOUNT=/opt/shared/letsencrypt-2-staging
CERT_NAME=xai-corp.net

LOG=$(mktemp)

###

run() {
  if [ "$ENVIRONMENT" == 'prod' ]; then
    LETSENCRYPT_MOUNT=/opt/shared/letsencrypt-2
  fi

  if $FIX; then
    fix
  else
    update
  fi
}

update() {
  export DOCKER_HOST=${DOCKER_HOST:-'dkhost:2376'}
  export LETSENCRYPT_MOUNT
  export LETSENCRYPT_IMAGE
  export CERT_NAME

  echo "Updating ${ENVIRONMENT}"

  # shellcheck disable=SC2086
  docker-compose \
    -f docker-compose.tools.yml \
    run --rm --name sslproxy_renew \
    renew ${OPTIONS}
}

fix() {
  export DOCKER_HOST=${DOCKER_HOST:-'home:2376'}
  export LETSENCRYPT_MOUNT
  export LETSENCRYPT_IMAGE
  export CERT_NAME

  echo "Fixing ${ENVIRONMENT}"

  docker run --rm -p80:80 -v $LETSENCRYPT_MOUNT:/etc/letsencrypt $LETSENCRYPT_IMAGE certonly --standalone -n --cert-name $CERT_NAME
}

test_new_certs() {
  echo | openssl s_client -showcerts -servername gnupg.org -connect git.xai-corp.net:443 2>/dev/null \
   | openssl x509 -inform pem -noout -text \
   | grep 'Timestamp :'
}

restart_nginx() {
  export DOCKER_HOST=${DOCKER_HOST:-'dkhost:2376'}
  echo restarting nginx

  containers=$(docker ps -q --filter "status=running" --filter "name=sslproxy_app")
  for c in $containers; do
    echo -e "\033[94m$c\033[39m"
    docker exec -t $c nginx -s reload
  done
}

function trap_exit() {
  code=$?
  if [ $code -gt 0 ]; then
    echo
    rm "$LOG"
    echo -e "\033[31mFailed updating production certs \033[39m"
    exit $code
  fi

  rm "$LOG"
  echo -e "\033[32mSuccess:\033[39m ssl certs have been updated"
}
trap  trap_exit EXIT

print_usage() {
  printf "Usage: %s: [-b] [-t] [-s] \n" "$0"
  echo -r rollback
  echo -t smoke tests
  echo -s tag as latest
  echo -h help
  exit 0
}

######

ENVIRONMENT=dev
OPTIONS="--cert-name ${CERT_NAME}"
TEST_CERT=true
FIX=false
while getopts ftnpde: name
do
    case $name in
    d)
      OPTIONS="$OPTIONS --dry-run"
      ;;
    p)
        TEST_CERT=false
        ENVIRONMENT=prod
      ;;
    f)
        FIX=true
        ;;
    t)
      test_new_certs
      exit 0
      ;;
    n)
      restart_nginx
      exit 0
      ;;
    :)
      echo "Invalid option: $OPTARG requires an argument" 1>&2
      ;;
    *)    print_usage;;
    esac
done

if [ "$TEST_CERT" == "true" ]; then
  OPTIONS="$OPTIONS --test-cert"
fi

# shellcheck disable=SC2068
run $@
restart_nginx
test_new_certs
