#!/bin/bash
# manages domains which are authorized by the CA to get certificates

SPATH="$(dirname "$(readlink -f ${BASH_SOURCE[0]})")"    # dir of the script
SNAME="$(basename ${BASH_SOURCE[0]})"                    # name of the script

ASCEDSCONF='local site certbot'
ASCEDSLIBS='utils'

if [ ! -r "${SPATH}/asceds-head" ] ; then
   echo "No header ${SPATH}/asceds-head. Exiting"
   exit 9
fi

. ${SPATH}/asceds-head

asceds-authorized-domains-usage()
{
  cat << ENDUSAGE

Usage: asceds-authorized-domains [-h] [-a <domainname>,...] [-d <domainname>,...]

Manages domains which are authorized by the CA to get certificates
using this server's EABKID/EABHMACKEY

-h --> display usage and exit
-a <domainname>[,<domainname>,...] adds comma separated domain names
-d <domainname>[,<domainname>,...] deletes comma separated domain names

With no argument, displays current configuration and goes into interactive mode;
Deletes domain names from ${ASCEDSETCDIR}/asceds-certbot.conf
   ${ASCEDSWEBDIR}/etc/users.php and ${ASCEDSWEBDIR}/html/public/.htaccess.
   Deletes clients containing the removed domains from certbot and from 
   asceds on the cert manager; do not revoke the existing certificates.
Adds domain names to ${ASCEDSETCDIR}/asceds-certbot.conf
   ${ASCEDSWEBDIR}/etc/users.php and ${ASCEDSWEBDIR}/html/public/.htaccess. 

ENDUSAGE
exit 0
}

# initialize domain list to be added
ADDDOM=""

# initialize domain list to be deleted
DELDOM=""

# general validation and parse of the command line
for ARG in ${ARGS} ; do
   #echo "ARG=${ARG}"
   if [ "${ARG}" != "${ARG//[^-a-zA-Z0-9.,]/}" ] ; then
      asceds-error "Malformed argument ${ARG}"
   elif [ "${ARG}" == "-h" ] ; then
      asceds-authorized-domains-usage
   elif [ "${ARG}" == "-a" ] ; then
      shift
      if [[ "$1" != -* ]] && [ -n "$1" ] ; then
         # domain names should be lower case
         ADDDOM="${ADDDOM},$( cat <<< $1 | tr '[:upper:]' '[:lower:]' )"
      fi
   elif [ "${ARG}" == "-d" ] ; then
      shift
      if [[ "$1" != -* ]] && [ -n "$1" ] ; then
         # domain names should be lower case
         DELDOM="${DELDOM},$( cat <<< $1 | tr '[:upper:]' '[:lower:]' )"
      fi
   else
      shift
   fi
done

# run as root only
asceds-run-asroot

# list the current authorized domains
echo
if [ -z "${AUTHDOMAIN}" ] ; then
   echo "No authorized domains defined yet"
else
   echo "Authorized domains: $( cat <<< ${AUTHDOMAIN} | \
         sed -e 's/,/ /g' )"
fi
echo

if [ -z "${ADDDOM}" ] && [ -z "${DELDOM}" ] ; then
   YE=''
   echo -n "Make interactive changes? [y/N] "
   read YE   
   if [ "${YE}" == 'y' ] || [ "${YE}" == 'Y' ] ; then
      # interactive mode
      YE=''
      while [ "${YE}" != 'y' ] && [ "${YE}" != 'Y' ] ; do
   
         read -e -p "Please type domains to be ADDED: " ADDDOM0
         echo
         read -e -p "Please type domains to be REMOVED: " DELDOM0
         echo      

         # check and sanitize input
         ADDDOM=$( cat <<< ${ADDDOM0} | tr '[:upper:]' '[:lower:]' )
         if [ "${ADDDOM}" != "${ADDDOM//[^-_a-zA-Z0-9., ]/}" ] ; then
            asceds-warning "Malformed domain list ${ADDDOM}, skipping"
            ADDDOM=''
         elif [ -n "${ADDDOM}" ] ; then
            ADDDOM=$( cat <<< ${ADDDOM} | tr ',' ' ' | xargs | \
                      tr ' ' ',' )
         fi

         DELDOM=$( cat <<< ${DELDOM0} | tr '[:upper:]' '[:lower:]' )
         if [ "${DELDOM}" != "${DELDOM//[^-_a-zA-Z0-9., ]/}" ] ; then
            asceds-warning "Malformed SANS list ${DELDOM}, skipping"
            DELDOM=''
         elif [ -n "${DELDOM}" ] ; then
            DELDOM=$( cat <<< ${DELDOM} | tr ',' ' ' | xargs )
         fi
      
         echo
         echo "Domains to be added: ${ADDDOM}"
         echo "Domains to be deleted: ${DELDOM}"
      
         echo -n "Is this the desired change? [y/N] "
         read YE
      done
   fi
elif [ -n "${ADDDOM}" ] ; then
   # Cleaning
   ADDDOM=$( cat <<< ${ADDDOM} | sed -e 's/,/ /g' | xargs  )
   echo "Domains to be added: ${ADDDOM}"
elif [ -n "${DELDOM}" ] ; then
   DELDOM=$( cat <<< ${DELDOM} | sed -e 's/,/ /g' | xargs  )
   echo "Domains to be deleted: ${DELDOM}"
fi

# now we have the desired ${ADDDOM} and ${DELDOM}
# operate changes:
if [ -n "${DELDOM}" ] ; then
   # determine the list of hosts to be removed from certbot and asceds
   HSTSTOREM=''
   if [ "$( echo ${ASCEDSHOMEDIR}/*_cert.conf )" != \
        "${ASCEDSHOMEDIR}/*_cert.conf" ] ; then
      for HSTCONF in ${ASCEDSHOMEDIR}/*_cert.conf ; do
         if [ -r "${HSTCONF}" ] ; then
            HST=$( basename ${HSTCONF} )
            HST=${HST%%_*}
            
            # get host details
            asceds-parse-certconf "${HSTCONF}"
            if [ -z "${CLIENT_DOMAIN_NAME}" ] || \
               [ -z "${HST}" ] || \
               [ "${HST}" != "${CLIENT_DOMAIN_NAME}" ] ; then
               asceds-error "Client '${HST}' is misconfigured"
            fi
            TOREM=''
            for DELD in ${DELDOM} ; do
               HSTTEST=$( cat <<< ${CLIENT_DOMAIN_NAME// /} | \
                  sed -e "s/[,.]${DELD},//g ; s/[,.]${DELD}$//g ; \
                          s/^${DELD}$//g ; s/^${DELD},//g" )
               SANSTEST=$( cat <<< ${CLIENT_SANS_LIST// /} | \
                  sed -e "s/[,.]${DELD},//g ; s/[,.]${DELD}$//g ; \
                          s/^${DELD}$//g ; s/^${DELD},//g" )
               if [ "${CLIENT_DOMAIN_NAME// /}" != "${HSTTEST}" ] || \
                  [ "${CLIENT_SANS_LIST// /}" != "${SANSTEST}" ] ; then
                  TOREM='yes'
               fi   
            done
            if [ -n "${TOREM}" ] ; then
               HSTSTOREM="${HSTSTOREM} ${HST}"
            fi
         fi
      done
   fi
   if [ -n "${HSTSTOREM}" ] ; then
      echo
      echo "If the domain(s) ${DELDOM} are deleted,"
      echo "the following clients using these domain(s)"
      echo "will be removed from certbot and from asceds:"
      echo "${HSTSTOREM}"
      echo
      echo "The current certificates will not be revoked!"
      echo "This operation is not reversible!!!"
      YE=''
      echo -n "Do you want to continue? [y/N] "
      read YE
      if [ "${YE}" != "y" ] && [ "${YE}" != "Y" ] ; then
         echo "Domain deletion aborted"
         exit 0
      fi
      for TOREM in ${HSTSTOREM} ; do
         asceds-disable-host "${TOREM}"
      done
   fi

   # first delete domains
   for DELD in ${DELDOM} ; do
      AUTHDOMAIN=$( cat <<< ${AUTHDOMAIN} | sed -e "s/\b${DELD}\b//g" | \
         sed -e "s/,,*/,/g" | sed -e "s/^,//" | sed -e "s/,$//" )
      sed -i -e "s/\"${DELD}\"//g ; s/(\s*,/(/g ; s/,\s*)/)/g ; s/,\s*,/,/g" \
         ${ASCEDSWEBDIR}/etc/users.php
   done
   asceds-echo "Deleting from authorized domain list: ${AUTHDOMAIN}"
   asceds-refresh-var "${ASCEDSETCDIR}/asceds-certbot.conf" \
                      "AUTHDOMAIN" "${AUTHDOMAIN}"

##   TBD --> Remove clients containing the removed domains from certbot and from 
##   asceds on the cert manager; do not revoke the existing certificates.


fi

if [ -n "${ADDDOM}" ] ; then
   # then add domains
   AUTHDOMAIN="${AUTHDOMAIN},${ADDDOM// /,}"
fi

# check if no duplicates
asceds-comma-uniq "AUTHDOMAIN"
asceds-echo "Authorized domain list: ${AUTHDOMAIN}"
asceds-refresh-var "${ASCEDSETCDIR}/asceds-certbot.conf" \
                      "AUTHDOMAIN" "${AUTHDOMAIN}"

# refresh the website setup for consistency
asceds-refresh-webdomains

