

. /etc/jeancloud.env


# 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")"
  (grep '^[[:blank:]]*[^#][[:blank:]]*server_name' "$file" | sed 's/ _ / /g' | sed   's/server_name//g' | sed 's/default_server//g' | sed -e 's/^[[:space:]]*//' -e 's/;$//'  | sort -u)
  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
call nginx test
call nginx reload
depuis le main ou ici ? 
