#!/bin/bash
#< Script to scp httpd configuration from webservers

ECHO="/bin/echo"
MKDIR="/bin/mkdir"
LS="/bin/ls"
RM="/bin/rm"
SCP="/usr/bin/scp"
SSH="/usr/bin/ssh"

SERVER_GROUPS=( "GROUP1" "GROUP2" "GROUP3" )
GROUP1_WEB_SERVERS=( "server1" "server2" "server3" "server4" "server5" )
GROUP2_WEB_SERVERS=( "server6" "server7" "server8" )
GROUP3_WEB_SERVERS=( "servera" "serverb" "serverc" "serverd" )

TARGET_BASE="/home/prodlogs/httpd_conf/config"

function print_error {
   ${ECHO} "Error: $@" >&2
}

function check_target {
   if [ ! -d "${TARGET_BASE}" ]; then
      print_error "Target directory does not exist" && exit 1
   fi
}

function main_logic {
  for SERVER_GROUP in ${SERVER_GROUPS[@]}; do
     eval SERVERS=\${${SERVER_GROUP}_WEB_SERVERS[@]}
     case ${SERVER_GROUP} in
        "GROUP3")	
           CONF_HOME="/etc/apache2"
           for SERVER in ${SERVERS}; do
              ${RM} -rf ${TARGET_BASE}/${SERVER}
              if [ ! -d "${TARGET_BASE}/${SERVER}" ]; then
                 ${MKDIR} ${TARGET_BASE}/${SERVER}
              fi
              ${SSH} ${SERVER} ${LS} -laR ${CONF_HOME} > ${TARGET_BASE}/${SERVER}/${SERVER}.ls-lR
              ${SCP} -q -r ${SERVER}:${CONF_HOME} ${TARGET_BASE}/${SERVER}
           done
           ;;
        *)
           CONF_HOME="/usr/local/apache/conf"
           for SERVER in ${SERVERS}; do
              ${RM} -rf ${TARGET_BASE}/${SERVER}
              if [ ! -d "${TARGET_BASE}/${SERVER}" ]; then
                 ${MKDIR} ${TARGET_BASE}/${SERVER}
              fi
              ${SSH} ${SERVER} ${LS} -laR ${CONF_HOME} > ${TARGET_BASE}/${SERVER}/${SERVER}.ls-lR
              ${SCP} -q -r ${SERVER}:${CONF_HOME} ${TARGET_BASE}/${SERVER}
           done
           ;;
     esac
  done
}

check_target
main_logic

exit 0