#!/bin/bash
################################################################################
#    HPCC SYSTEMS software Copyright (C) 2019 HPCC Systems®.
#
#    Licensed under the Apache License, Version 2.0 (the "License");
#    you may not use this file except in compliance with the License.
#    You may obtain a copy of the License at
#
#       http://www.apache.org/licenses/LICENSE-2.0
#
#    Unless required by applicable law or agreed to in writing, software
#    distributed under the License is distributed on an "AS IS" BASIS,
#    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#    See the License for the specific language governing permissions and
#    limitations under the License.
################################################################################

set -x
exec 3>&2 2>./distributePKI.log

INSTALL_DIR=/opt/HPCCSystems
CONFIG_DIR=/etc/HPCCSystems
ENV_XML_FILE=environment.xml
ENV_CONF_FILE=environment.conf
PID_DIR=/var/run/HPCCSystems
LOCK_DIR=/var/lock/HPCCSystems
LOG_DIR=/var/log/HPCCSystems
INIT_PATH=/etc/init.d


progname=distributePKI

source ${INSTALL_DIR}/etc/init.d/hpcc_common
source ${INSTALL_DIR}/etc/init.d/init-functions
source ${INSTALL_DIR}/etc/init.d/export-path

HPCC_CONFIG=${HPCC_CONFIG:-${CONFIG_DIR}/${ENV_CONF_FILE}}
SECTION=${1:-DEFAULT}
PATH_PREFIX=`cat ${HPCC_CONFIG} | sed -n "/\[${SECTION}\]/,/\[/p" | grep "^home *= *" | sed -e 's/^home *= *//'`
USER_NAME=`cat ${HPCC_CONFIG} | sed -n "/\[${SECTION}\]/,/\[/p" | grep "^user *= *" | sed -e 's/^user *= *//'`
homePath=${PATH_PREFIX}/${USER_NAME}

certPath=${homePath}/certificate
sbin_path="${INSTALL_DIR}/sbin"
envfile="${CONFIG_DIR}/${ENV_XML_FILE}"

source_file=certificates.tgz
source_tar=${homePath}/${source_file}

if [ "$(whoami)" != "root" ] && [ "$(whoami)" != "${USER_NAME}" ]; then
   echo ""
   echo "The script must run as root, $USER_NAME or sudo."
   echo ""
   exit 1
fi

createScriptFile() {

  cat > $SCRIPT_FILE <<SCRIPTFILE
#!/bin/bash
IP=\$1

if ping -c 1 -w 5 -n \$IP > /dev/null 2>&1; then
  echo "\$IP: Host is alive."
  CAN_SSH="\`ssh -i $homePath/.ssh/id_rsa -o BatchMode=yes -o LogLevel=QUIET -o StrictHostKeyChecking=no $USER_NAME@\$IP exit > /dev/null 2>&1; echo \$?\`"
  if [ "\$CAN_SSH" -eq 255 ]; then
    echo "\$IP: Cannot SSH to host.";
  fi
  
  IS_LOCAL="\`ssh -i $homePath/.ssh/id_rsa -o BatchMode=yes -o LogLevel=QUIET -o StrictHostKeyChecking=no $USER_NAME@\$IP ls $SCRIPT_FILE > /dev/null 2>&1; echo \$?\`"
  if [ "\$IS_LOCAL" -ne 0 ]; then
    echo "\$IP: Fetching complist for \$IP"
  else
    echo "\$IP: running on local machine, nothing to do"
    exit 0
  fi
  
  ## get list of components on remote machine
  OIFS=\$IFS
  IFS=\$'\\n'
  complist=(\$($sbin_path/configgen -env $envfile -ip \$IP -list | awk 'BEGIN { FS="=";} {print \$1;}'))
  IFS=\$OIFS
  
  ## ensure certPath exists
  ssh -i $homePath/.ssh/id_rsa -o BatchMode=yes -o LogLevel=QUIET -o StrictHostKeyChecking=no $USER_NAME@\$IP mkdir -p $certPath > /dev/null 2>&1

  ssh -i $homePath/.ssh/id_rsa -o BatchMode=yes -o LogLevel=QUIET -o StrictHostKeyChecking=no $USER_NAME@\$IP rm -f $certPath/public.key.pem $certPath/key.pem $certPath/certificate.pem > /dev/null 2>&1
  scp -i $homePath/.ssh/id_rsa $certPath/public.key.pem $certPath/key.pem $certPath/certificate.pem $USER_NAME@\$IP:$certPath

  for i in \${complist[@]} ; do
      ## allow for overwrite
      ssh -i $homePath/.ssh/id_rsa -o BatchMode=yes -o LogLevel=QUIET -o StrictHostKeyChecking=no $USER_NAME@\$IP rm -rf $certPath/\$i > /dev/null 2>&1
      echo "\$IP: scp -r $certPath/\$i $certPath";
      scp -r -i $homePath/.ssh/id_rsa $certPath/\$i $USER_NAME@\$IP:$certPath
  done

else
  echo "\$IP: Cannot Ping host? (Host Alive?)"
  exit 1
fi
SCRIPTFILE

chmod +x ${SCRIPT_FILE}
}

createRemoteToRemoteScriptFile() {

  cat > $SCRIPT_FILE <<REMOTE_TO_REMOTE_SCRIPTFILE
#!/bin/bash
IP=\$1

if ping -c 1 -w 5 -n \$IP > /dev/null 2>&1; then
  echo "\$IP: Host is alive."
  CAN_SSH="\`ssh -i $homePath/.ssh/id_rsa -o BatchMode=yes -o LogLevel=QUIET -o StrictHostKeyChecking=no $USER_NAME@\$IP exit > /dev/null 2>&1; echo \$?\`"
  if [ "\$CAN_SSH" -eq 255 ]; then
    echo "\$IP: Cannot SSH to host.";
  fi
 
  if [ "$dali_ip" == "\$IP" ]; then
    echo "\$IP: On admin node, nothing to do"
    exit 0
  fi
  
  ## get list of components on remote machine
  OIFS=\$IFS
  IFS=\$'\\n'
  complist=(\$($sbin_path/configgen -env $envfile -ip \$IP -list | awk 'BEGIN { FS="=";} {print \$1;}'))
  IFS=\$OIFS
  
  ## ensure certPath exists
  ssh -i $homePath/.ssh/id_rsa -o BatchMode=yes -o LogLevel=QUIET -o StrictHostKeyChecking=no $USER_NAME@\$IP mkdir -p $certPath > /dev/null 2>&1

  ssh -i $homePath/.ssh/id_rsa -o BatchMode=yes -o LogLevel=QUIET -o StrictHostKeyChecking=no $USER_NAME@\$IP rm -f $certPath/public.key.pem $certPath/key.pem $certPath/certificate.pem > /dev/null 2>&1
  scp -i $homePath/.ssh/id_rsa $USER_NAME@$dali_ip:$certPath/public.key.pem $USER_NAME@\$IP:$certPath
  scp -i $homePath/.ssh/id_rsa $USER_NAME@$dali_ip:$certPath/key.pem $USER_NAME@\$IP:$certPath
  scp -i $homePath/.ssh/id_rsa $USER_NAME@$dali_ip:$certPath/certificate.pem $USER_NAME@\$IP:$certPath

  for i in \${complist[@]} ; do
      ## allow for overwrite
      ssh -i $homePath/.ssh/id_rsa -o BatchMode=yes -o LogLevel=QUIET -o StrictHostKeyChecking=no $USER_NAME@\$IP rm -rf $certPath/\$i > /dev/null 2>&1
      echo "\$IP: scp -r $certPath/\$i $certPath";
      scp -r -i $homePath/.ssh/id_rsa $USER_NAME@$dali_ip:$certPath/\$i $USER_NAME@\$IP:$certPath
  done

else
  echo "\$IP: Cannot Ping host? (Host Alive?)"
  exit 1
fi
REMOTE_TO_REMOTE_SCRIPTFILE

chmod +x ${SCRIPT_FILE}
}

is_dali=$($sbin_path/configgen -env $envfile -list | grep dali )
if [ -n "$is_dali" ]; then
  SCRIPT_FILE=/tmp/distributePKI_$$
  createScriptFile

  ${INSTALL_DIR}/etc/init.d/setupPKI

  OPTION="-e ${CONFIG_DIR}/${ENV_CONF_FILE} -s ${SECTION:-DEFAULT} -x"
  eval ${INSTALL_DIR}/sbin/cluster_script.py -f ${SCRIPT_FILE} $OPTION
  rm -rf ${SCRIPT_FILE}
else
  SCRIPT_FILE=/tmp/distributePKI_$$
  dali_ip=$($sbin_path/configgen -env $envfile -listall | awk 'BEGIN {FS=",";} /^DaliServerProcess/ {print $3;}')
  createRemoteToRemoteScriptFile
  ssh -i $homePath/.ssh/id_rsa -o BatchMode=yes -o LogLevel=QUIET -o StrictHostKeyChecking=no $USER_NAME@$dali_ip $INSTALL_DIR/etc/init.d/setupPKI
  OPTION="-e ${CONFIG_DIR}/${ENV_CONF_FILE} -s ${SECTION:-DEFAULT}"
  eval ${INSTALL_DIR}/sbin/cluster_script.py -f ${SCRIPT_FILE} $OPTION
  rm -rf ${SCRIPT_FILE}
fi

set +x
