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

script=$(basename "$0")
version="1.0.1"

help() {
    echo
    echo "$script"
    echo
    echo 'Description: Delete Certbot certificate.'
    echo "Syntax: $script [-c|-d|help]"
    echo 'Example: $script -c example.odoo.com -d /usr/share/certbot01'
    echo 'options:'
    echo '  -c    Certificate name.'
    echo '  -d    Certbot data dir.'
    echo "  help  Show $script manual."
    echo
}

if [[ "$1" == 'help' ]]; then
    help
    exit
fi

while getopts ":c: :d:" opt; do
  case $opt in
    c) certificate="$OPTARG"
    ;;
    d) certbot_data_dir="$OPTARG"
    ;;
    \?) echo "Invalid option -$OPTARG" >&2
    help
    exit 1;;
  esac
done

[[ -z "$certificate" ]] && { echo 'Parameter -c|certificate is empty.' ; exit 1; }
[[ -z "$certbot_data_dir" ]] && { echo 'Parameter -d|certbot data dir is empty.' ; exit 1; }

read -p "Please confirm the deletion of $certificate in $certbot_data_dir (y/n)? " reply
if [[ $reply == y ]]; then
  echo "Deleting certificate $certificate ..."

  docker run --rm --name "${certificate}-tmp" \
  -v "$certbot_data_dir/:/etc/letsencrypt/" \
  -v "$certbot_data_dir/www/:/var/www/certbot/" \
  certbot/certbot \
  delete --cert-name $certificate --non-interactive

fi
