#!/bin/bash
# This script will run on new cert and on cron renew
# there is one cert by service

set -u

. /etc/jeancloud.env

# TODO make it an ansible script
# No

# Les arguments du pauvre
if [ "$#" -eq 1 ] && [ "$1" = '-v' ] ; then
  verbose=true
else
  verbose=false
fi

# Variable
acmeroot=/var/www/letsencrypt

# Création du répertoire
mkdir -p "$acmeroot"


for file in "$nginx_conf_path"* ; do
  if $verbose ; then
    echo '-------------------------'
    echo "$file"
  fi

  service_name="$(basename "$file")"

  if [ -d "$dns_certs_path/$service_name" ] ; then
	  echo "$service_name is handled by dnscerts"
	  continue
  fi
    
  # Getting just the domain names
  domains="$(extract_domain_nginx_conf.sh "$file")"
  if [ -n "$domains" ] ; then
    # If using dummy cert, disabling it
	dummy_cert.sh "$service_name" remove

    echo "$domains"
    # adding -d before every domain
    domains="-d $(echo $domains | sed 's/ / -d /g')"

    # Run certbot
    command="certbot certonly -n --expand --agree-tos --webroot -w "$acmeroot" --email contact@jean-cloud.org --cert-name "$(basename $file)" $domains"
    if $verbose ; then
      echo $command
    fi
    out="$($command 2>&1)"
    result="$?"
    
    if [ "$result" -eq 0 ] && [[ "$out" = *"Certificate not yet due for renewal; no action taken."* ]]; then
      echo "Cert still valid"
    elif [ "$result" -eq 0 ] ; then
      echo "Cert renewed or obtained"
      #new_cert="$(echo "$out" | grep -oE '/etc/letsencrypt/live/.*/fullchain.pem')"
      #echo "'$new_cert'"
      #new_cert_dir="$(dirname "$out")"
      #echo "'$new_cert_dir'"
    
      #if [ -d "$new_cert_dir" ] ; then
      #  echo "New cert dir : '$new_cert_dir'"
      #  echo "cp '$new_cert_dir/*' '/data/proxy/certs/'"
      #else
      #  echo "Error parsiong dir name"
      #fi
    
    elif [ "$result" -eq 1 ] ; then
      echo "Cert failed"
      echo "     ------------------------------------------"
      echo "$out"
      echo "     ------------------------------------------"
    else
        echo "Unknown error : $result.\n$out"
    fi
  fi
done

ls /etc/letsencrypt/live/*000* &> /dev/null
if [ "$?" -eq 0 ] ; then
    echo " ---------------------------------------------------------------------------------------------"
    echo "Bad certs detected in letsencrypt dir. Nginx conf wont work…"
    echo "rm -r /etc/letsencrypt/live/*000* /etc/letsencrypt/archive/*000* /etc/letsencrypt/renewal/*000*"
    echo " ---------------------------------------------------------------------------------------------"
fi


nginx -t
code="$?"
if [ "$code" -ne 0 ] ; then
    echo "Nginx test error, can’t reloat it"
    exit 1
fi

nginx -s reload
code="$?"
if [ "$code" -ne 0 ] ; then
    echo "Nginx reload error, GENERAL ALEEEEEEEEERT!!!!!"
    exit 1
fi
echo "Done. No error detected."
