#!/bin/bash
# tests read/write scp access to asceds@client

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-website-head" ] ; then
   echo "No header ${SPATH}/asceds-website-head. Exiting"
   exit 9
fi

. ${SPATH}/asceds-website-head

asceds-test-return-usage()
{
  cat << ENDUSAGE

Tests read/write scp access to asceds@client

asceds-test-return [-h] -c <client_name>
-h --> display usage and exit
-c <client_name> --> client name to test 

Outputs: success = read/write successful 
         readonly = read-only access 
         noaccess = no ssh access at all

ENDUSAGE
exit 0
}

# client to use with the -c option
CLIENT_NAME=''

# 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
      shift
      asceds-test-return-usage
   elif [ "${ARG}" == "-c" ] ; then
      shift
      if [[ "$1" != -* ]] && [ -n "$1" ] ; then
         CLIENT_NAME=$( cat <<< $1 | tr '[:upper:]' '[:lower:]' )
         asceds-expand-hostname "${CLIENT_NAME}" && \
            CLIENT_NAME="${ASCEDS_FQDN}"
         asceds-validate-fqdn "${CLIENT_NAME}" || \
            asceds-error "Invalid client FQDN ${CLIENT_NAME}"
      fi
   else
      shift
   fi
done

# checks on client name
if [ -z "${CLIENT_NAME}" ] ; then
   asceds-error "No client name passwed as argument"
fi


# returns "0"=read/write successful, "1"=read-only, "2"=no ssh access at all
asceds-test-remoterw "${CLIENT_NAME}" > /dev/null 2>&1
SSHTEST=$?
if [ "${SSHTEST}" = '0' ] ; then
   TESTRES="success"
elif [ "${SSHTEST}" = '1' ] ; then
   TESTRES="readonly"
elif [ "${SSHTEST}" = '2' ] ; then
   TESTRES="noaccess"
fi

if [ "${TESTRES}" == "success" ] ; then
   eval sudo -u asceds -i ${SCP} asceds@${CLIENT_NAME}:cert.conf \
     ${ASCEDSHOMEDIR}/${CLIENT_NAME}_cert.conf.client > /dev/null 2>&1 \
     || TESTRES="nocertconf"
fi

if [ -f "${ASCEDSHOMEDIR}/${CLIENT_NAME}_cert.conf.client" ] ; then
   ${RM} -f ${ASCEDSHOMEDIR}/${CLIENT_NAME}_cert.conf.client > /dev/null
fi

echo "${TESTRES}"


