#!/bin/sh 
# IBM(c) 2007 EPL license http://www.eclipse.org/legal/epl-v10.html
#(C)IBM Corp
#  This script adds xCAT specific setup to the /etc/ssh/sshd_config and ssh_config file
#  It calls getcredentials.awk to get from the xcatmaster  ssh host keys from the 
#  /etc/xcat/hostkeys directory and puts in  /etc/ssh on the node the following keys
#     ssh_host_dsa_key,ssh_host_rsa_key, ssh_host_ecdsa_key (if supported) 
#  It calls getcredentials.awk to get from the xcatmaster root ssh keys from the
#  ~/.ssh directory on the xcatmaster and put in ~/.ssh on the node the following keys:
#   If site.enablesshbetweennodes is yes
#      id.rsa
#
# if on the Management Node, exit


if [ "$(uname -s|tr 'A-Z' 'a-z')" = "linux" ];then
   str_dir_name=`dirname $0`
   . $str_dir_name/xcatlib.sh
fi

if [ -e /etc/xCATMN ]; then
	logger -t xcat -p local4.info "remoteshell:Running on the Management Node ,  exiting "
   exit 0
fi
# if -p input, do special PCM setup 
if [ -n "$1" ]; then
 if [ $1 = "-p" ]; then 
    SETUPFORPCM=1
 fi
fi


#  Linux or if AIX call aixremoteshell -d 
if [ "$(uname -s)" = "AIX" ]; then
   ./aixremoteshell -d 2>&1 
	logger -t xcat -p local4.info "Install: On AIX , remoteshell calling aixremoteshell -d "
   exit 0
fi
master=$MASTER
# are we using xcat flow control
useflowcontrol=0
if [ "$USEFLOWCONTROL" = "YES" ] || [ "$USEFLOWCONTROL" = "yes" ] || [ "$USEFLOWCONTROL" = "1" ]; then
  useflowcontrol=1
fi    

if [ -r /etc/ssh/sshd_config ]
then
	logger -t xcat -p local4.info "remoteshell:  setup /etc/ssh/sshd_config and ssh_config"
	cp /etc/ssh/sshd_config /etc/ssh/sshd_config.ORIG
        #delete all occurance of the attribute and then add xCAT settings
        sed -i '/X11Forwarding /'d /etc/ssh/sshd_config
        echo "X11Forwarding yes" >>/etc/ssh/sshd_config
        sed -i '/KeyRegenerationInterval /'d /etc/ssh/sshd_config
        echo "KeyRegenerationInterval 0" >>/etc/ssh/sshd_config
        sed -i '/MaxStartups /'d /etc/ssh/sshd_config
        echo "MaxStartups 1024" >>/etc/ssh/sshd_config
 
    if [ "$SETUPFORPCM" = "1" ];then
         sed -i '/PasswordAuthentication /'d /etc/ssh/sshd_config
         echo "PasswordAuthentication yes" >>/etc/ssh/sshd_config

    fi
fi

if [ -r /etc/ssh/ssh_config ]
then
   sed -i '/StrictHostKeyChecking /'d /etc/ssh/ssh_config
   echo "StrictHostKeyChecking no" >> /etc/ssh/ssh_config

fi
xcatpost="xcatpost"
if [ -d /xcatpost/_ssh ]
then
	logger -p local4.info -t xcat "Install: setup root .ssh"
	cd /xcatpost/_ssh
	mkdir -p /root/.ssh
	cp -f * /root/.ssh
   cd - >/dev/null
	chmod 700 /root/.ssh
	chmod 600 /root/.ssh/*
fi

if [ ! -x /usr/bin/openssl ]; then
    logger -t xcat -p local4.err "Install: /usr/bin/openssl is not executable."
    exit 0
fi
allowcred.awk &
CREDPID=$!
sleep 1

#download the ssh host dsa private keys
if [ $useflowcontrol = "1" ]; then
  #first contact daemon  xcatflowrequest <server> 3001
  logger -t xCAT -p local4.info "remoteshell: sending xcatflowrequest $master 3001"
 /$xcatpost/xcatflowrequest $master 3001
 rc=$? 
 logger -t xCAT -p local4.info "remoteshell:xcatflowrequest received response return=$rc" 
 if [ $rc -ne 0 ]; then
      logger -t xCAT -p local4.info "remoteshell: error from xcatflowrequest, will not use flow control"
      useflowcontrol=0
 fi

 
fi
getcredentials.awk ssh_dsa_hostkey | grep -E -v '</{0,1}xcatresponse>|</{0,1}serverdone>' | sed -e 's/&lt;/</' -e 's/&gt;/>/' -e 's/&amp;/&/' -e 's/&quot/"/' -e "s/&apos;/'/" > /tmp/ssh_dsa_hostkey

#check the message is an error or not
grep -E '<error>' /tmp/ssh_dsa_hostkey
if [ $? -ne 0 ]; then
	#the message received is the data
	cat /tmp/ssh_dsa_hostkey | grep -E -v '</{0,1}errorcode>|/{0,1}data>|</{0,1}content>|</{0,1}desc>' >/etc/ssh/ssh_host_dsa_key
	logger -t xCAT -p local4.info "remoteshell: getting ssh_host_dsa_key"
   MAX_RETRIES=10
   RETRY=0
   MYCONT=`cat /etc/ssh/ssh_host_dsa_key`
   while [ -z "$MYCONT" ]; do
              # not using flow control , need to sleep         
              if [ $useflowcontrol = "0" ]; then
                let SLI=$RANDOM%10
                let SLI=SLI+10
                sleep $SLI
              fi
 
                RETRY=$(($RETRY+1))
                if [ $RETRY -eq $MAX_RETRIES ]
                then
                  break
                fi
                if [ $useflowcontrol = "1" ]; then
                  #first contact daemon  xcatflowrequest <server> 3001
                  logger -t xCAT -p local4.info "remoteshell: sending xcatflowrequest $master 3001"
                  /$xcatpost/xcatflowrequest $master 3001
                  rc=$? 
                  logger -t xCAT -p local4.info "remoteshell:xcatflowrequest return=$rc" 
                  if [ $rc -ne 0 ]; then
                     logger -t xCAT -p local4.info "remoteshell: error from xcatflowrequest, will not use flow control"
                     useflowcontrol=0
                  fi
                fi
                getcredentials.awk ssh_dsa_hostkey | grep -v '<'|sed -e 's/&lt;/</' -e 's/&gt;/>/' -e 's/&amp;/&/' -e 's/&quot/"/' -e "s/&apos;/'/" > /etc/ssh/ssh_host_dsa_key
                MYCONT=`cat /etc/ssh/ssh_host_dsa_key`
   done
   chmod 600 /etc/ssh/ssh_host_dsa_key
   if ! grep "PRIVATE KEY" /etc/ssh/ssh_host_dsa_key > /dev/null 2>&1 ; then
        rm /etc/ssh/ssh_host_dsa_key
	else
		ssh-keygen -y -f /etc/ssh/ssh_host_dsa_key > /etc/ssh/ssh_host_dsa_key.pub
		chmod 644 /etc/ssh/ssh_host_dsa_key.pub
		chown root /etc/ssh/ssh_host_dsa_key.pub
   fi
else 
	#the message received is an error, so parse it
	ERR_MSG=`sed -n 's%.*<error>\(.*\)</error>.*%\1%p' /tmp/ssh_dsa_hostkey`
	logger -t xCAT -p local4.err Error: $ERR_MSG
fi
rm /tmp/ssh_dsa_hostkey

# download the host rsa key
if [ $useflowcontrol = "1" ]; then
  #first contact daemon  xcatflowrequest <server> 3001
  logger -t xCAT -p local4.info "remoteshell: sending xcatflowrequest $master 3001"
  /$xcatpost/xcatflowrequest $master 3001
  rc=$? 
  logger -t xCAT -p local4.info "remoteshell:xcatflowrequest return=$rc" 
  if [ $rc -ne 0 ]; then
      logger -t xCAT -p local4.info "remoteshell: error from xcatflowrequest, will not use flow control"
      useflowcontrol=0
  fi
fi

getcredentials.awk ssh_rsa_hostkey | grep -E -v '</{0,1}xcatresponse>|</{0,1}serverdone>' | sed -e 's/&lt;/</' -e 's/&gt;/>/' -e 's/&amp;/&/' -e 's/&quot/"/' -e "s/&apos;/'/" > /tmp/ssh_rsa_hostkey

#check whether the message is an error or not
grep -E '<error>' /tmp/ssh_rsa_hostkey
if [ $? -ne 0 ]; then
	#the message received is the data we request
	cat /tmp/ssh_rsa_hostkey | grep -E -v '</{0,1}errorcode>|/{0,1}data>|</{0,1}content>|</{0,1}desc>' >/etc/ssh/ssh_host_rsa_key
	logger -t xCAT -p local4.info ssh_rsa_hostkey
	MYCONT=`cat /etc/ssh/ssh_host_rsa_key`
   MAX_RETRIES=10
   RETRY=0
	while [ -z "$MYCONT" ]; do
              # not using flow control , need to sleep         
              if [ $useflowcontrol = "0" ]; then
                let SLI=$RANDOM%10
                let SLI=SLI+10
                sleep $SLI
              fi
                RETRY=$(($RETRY+1))
                if [ $RETRY -eq $MAX_RETRIES ]
                then
                  break
                fi
                if [ $useflowcontrol = "1" ]; then
                  #first contact daemon  xcatflowrequest <server> 3001
                  logger -t xCAT -p local4.info "remoteshell: sending xcatflowrequest $master 3001"
                  /$xcatpost/xcatflowrequest $master 3001
                  rc=$? 
                  logger -t xCAT -p local4.info "remoteshell:xcatflowrequest return=$rc" 
                  if [ $rc -ne 0 ]; then
                      logger -t xCAT -p local4.info "remoteshell: error from xcatflowrequest, will not use flow control"
                      useflowcontrol=0
                  fi
                fi

    		getcredentials.awk ssh_rsa_hostkey | grep -v '<'|sed -e 's/&lt;/</' -e 's/&gt;/>/' -e 's/&amp;/&/' -e 's/&quot/"/' -e "s/&apos;/'/" > /etc/ssh/ssh_host_rsa_key
    		MYCONT=`cat /etc/ssh/ssh_host_rsa_key`
	done
	chmod 600 /etc/ssh/ssh_host_rsa_key
	if ! grep "PRIVATE KEY" /etc/ssh/ssh_host_rsa_key > /dev/null 2>&1 ; then
   		rm /etc/ssh/ssh_host_rsa_key
	else
		ssh-keygen -y -f /etc/ssh/ssh_host_rsa_key > /etc/ssh/ssh_host_rsa_key.pub
		chmod 644 /etc/ssh/ssh_host_rsa_key.pub
		chown root /etc/ssh/ssh_host_rsa_key.pub
	fi
else
	#This is an error message
	ERR_MSG=`sed -n 's%.*<error>\(.*\)</error>.*%\1%p' /tmp/ssh_rsa_hostkey`
	logger -t xCAT -p local4.err Error: $ERR_MSG
fi
rm /tmp/ssh_rsa_hostkey

# if there is a ecdsa host key on the node then download the replacement from the MN/SN
if [ -f /etc/ssh/ssh_host_ecdsa_key ]; then
  # download the host ecdsa key
  if [ $useflowcontrol = "1" ]; then
    #first contact daemon  xcatflowrequest <server> 3001
    logger -t xCAT -p local4.info "remoteshell: sending xcatflowrequest $master 3001"
    /$xcatpost/xcatflowrequest $master 3001
    rc=$? 
    logger -t xCAT -p local4.info "remoteshell:xcatflowrequest return=$rc" 
    if [ $rc -ne 0 ]; then
      logger -t xCAT -p local4.info "remoteshell: error from xcatflowrequest, will not use flow control"
      useflowcontrol=0
    fi
  fi

  getcredentials.awk ssh_ecdsa_hostkey | grep -E -v '</{0,1}xcatresponse>|</{0,1}serverdone>' | sed -e 's/&lt;/</' -e 's/&gt;/>/' -e 's/&amp;/&/' -e 's/&quot/"/' -e "s/&apos;/'/" > /tmp/ssh_ecdsa_hostkey

  #check whether the message is an error or not
  grep -E '<error>' /tmp/ssh_ecdsa_hostkey
  if [ $? -ne 0 ]; then
	#the message received is the data we request
	cat /tmp/ssh_ecdsa_hostkey | grep -E -v '</{0,1}errorcode>|/{0,1}data>|</{0,1}content>|</{0,1}desc>' >/etc/ssh/ssh_host_ecdsa_key
	logger -t xCAT -p local4.info ssh_ecdsa_hostkey
	MYCONT=`cat /etc/ssh/ssh_host_ecdsa_key`
   MAX_RETRIES=10
   RETRY=0
	while [ -z "$MYCONT" ]; do
              # not using flow control , need to sleep         
              if [ $useflowcontrol = "0" ]; then
                let SLI=$RANDOM%10
                let SLI=SLI+10
                sleep $SLI
              fi
                RETRY=$(($RETRY+1))
                if [ $RETRY -eq $MAX_RETRIES ]
                then
                  break
                fi
                if [ $useflowcontrol = "1" ]; then
                  #first contact daemon  xcatflowrequest <server> 3001
                  logger -t xCAT -p local4.info "remoteshell: sending xcatflowrequest $master 3001"
                  /$xcatpost/xcatflowrequest $master 3001
                  rc=$? 
                  logger -t xCAT -p local4.info "remoteshell:xcatflowrequest return=$rc" 
                  if [ $rc -ne 0 ]; then
                      logger -t xCAT -p local4.info "remoteshell: error from xcatflowrequest, will not use flow control"
                      useflowcontrol=0
                  fi
                fi

    		getcredentials.awk ssh_ecdsa_hostkey | grep -v '<'|sed -e 's/&lt;/</' -e 's/&gt;/>/' -e 's/&amp;/&/' -e 's/&quot/"/' -e "s/&apos;/'/" > /etc/ssh/ssh_host_ecdsa_key
    		MYCONT=`cat /etc/ssh/ssh_host_ecdsa_key`
	done
	chmod 600 /etc/ssh/ssh_host_ecdsa_key
	if ! grep "PRIVATE KEY" /etc/ssh/ssh_host_ecdsa_key > /dev/null 2>&1 ; then
   		rm /etc/ssh/ssh_host_ecdsa_key
	else
		ssh-keygen -y -f /etc/ssh/ssh_host_ecdsa_key > /etc/ssh/ssh_host_ecdsa_key.pub
		chmod 644 /etc/ssh/ssh_host_ecdsa_key.pub
		chown root /etc/ssh/ssh_host_ecdsa_key.pub
	fi
  else
	#This is an error message
	ERR_MSG=`sed -n 's%.*<error>\(.*\)</error>.*%\1%p' /tmp/ssh_ecdsa_hostkey`
	logger -t xCAT -p local4.err Error: $ERR_MSG
  fi
  rm /tmp/ssh_ecdsa_hostkey
fi

if [[ $NTYPE = service ]]; then
   mkdir -p /etc/xcat/hostkeys
   cp /etc/ssh/ssh* /etc/xcat/hostkeys/.
fi

umask 0077 
# This is where we start getting root ssh keys
# This tells credentials.pm where to get the root .ssh keys.  If no zone then old path of ~.ssh
#rootsshpvtkey=ssh_root_key:$zonename
mkdir -p /root/.ssh/
# this is for obtaining non-zone keys
rootsshpvtkey=ssh_root_key
rootsshpubkey=ssh_root_pub_key
if [ $ZONENAME ];
then 
# This tells credentials.pm where to get the root .ssh keys.  If no zone then old path of ~/.ssh
  zonename=$ZONENAME
  rootsshpvtkey=ssh_root_key:$zonename
  rootsshpubkey=ssh_root_pub_key:$zonename
  logger -t xCAT -p local4.info "remoteshell: gathering root ssh keys for $zonename"
    
fi

# always get  the id_rsa.pub key for the node and put in authorized_keys 
if [ $useflowcontrol = "1" ]; then
  #first contact daemon  xcatflowrequest <server> 3001
  logger -t xCAT -p local4.info "remoteshell: sending xcatflowrequest $master 3001"
  /$xcatpost/xcatflowrequest $master 3001
  rc=$? 
  logger -t xCAT -p local4.info "remoteshell:xcatflowrequest return=$rc" 
  if [ $rc -ne 0 ]; then
    logger -t xCAT -p local4.info "remoteshell: error from xcatflowrequest, will not use flow control"
    useflowcontrol=0
  fi
fi

  getcredentials.awk $rootsshpubkey  | grep -E -v '</{0,1}xcatresponse>|</{0,1}serverdone>'|sed -e 's/&lt;/</' -e 's/&gt;/>/' -e 's/&amp;/&/' -e 's/&quot/"/' -e "s/&apos;/'/" > /tmp/ssh_root_pub_key

  logger -t xCAT -p local4.info "remoteshell: gathering $rootsshpubkey "
  #check whether the message is an error or not
  grep -E '<error>' /tmp/ssh_root_pub_key
if [ $? -ne 0 ]; then
	#The message contains the data we request
	cat /tmp/ssh_root_pub_key | grep -E -v '</{0,1}errorcode>|</{0,1}data>|</{0,1}content>|</{0,1}desc>' > /root/.ssh/id_rsa.pub
        # no add to authorized_keys, so the node can ssh to itself
	cat /tmp/ssh_root_pub_key | grep -E -v '</{0,1}errorcode>|</{0,1}data>|</{0,1}content>|</{0,1}desc>' >> /root/.ssh/authorized_keys
	logger -t xCAT -p local4.info ssh_root_pub_key
	MYCONT=`cat /root/.ssh/id_rsa.pub`
   MAX_RETRIES=10
   RETRY=0
	while [ -z "$MYCONT" ]; do
                if [ $useflowcontrol = "0" ]; then
                 let SLI=$RANDOM%10
                 let SLI=SLI+10
                 sleep $SLI
                fi
                RETRY=$(($RETRY+1))
                if [ $RETRY -eq $MAX_RETRIES ]
                then
                  break
                fi
                if [ $useflowcontrol = "1" ]; then
                  #first contact daemon  xcatflowrequest <server> 3001
                  logger -t xCAT -p local4.info "remoteshell: sending xcatflowrequest $master 3001"
                  /$xcatpost/xcatflowrequest $master 3001
                  rc=$? 
                  logger -t xCAT -p local4.info "remoteshell:xcatflowrequest return=$rc" 
                  if [ $rc -ne 0 ]; then
                     logger -t xCAT -p local4.info "remoteshell: error from xcatflowrequest, will not use flow control"
                     useflowcontrol=0
                  fi
                fi
		          getcredentials.awk $rootsshpubkey | grep -v '<'|sed -e 's/&lt;/</' -e 's/&gt;/>/' -e 's/&amp;/&/' -e 's/&quot/"/' -e "s/&apos;/'/" > /root/.ssh/id_rsa.pub
		          getcredentials.awk $rootsshpubkey | grep -v '<'|sed -e 's/&lt;/</' -e 's/&gt;/>/' -e 's/&amp;/&/' -e 's/&quot/"/' -e "s/&apos;/'/" >> /root/.ssh/authorized_keys
		          MYCONT=`cat /root/.ssh/id_rsa.pub`
	done
else
	#This is an error message
	ERR_MSG=`sed -n 's%.*<error>\(.*\)</error>.*%\1%p' /tmp/ssh_root_pub_key`
	logger -t xCAT -p local4.err $rootsshpubkey Error: $ERR_MSG
fi
rm /tmp/ssh_root_pub_key

# if sshbetweennodes is enabled then we get id_rsa ( private key) 
if [ $ENABLESSHBETWEENNODES = "YES" ];  # want nodes to be able to ssh to each other without password
then 
 logger -t xCAT -p local4.info "remoteshell:sshbetweennodes is yes" 
 if [ $useflowcontrol = "1" ]; then
  #first contact daemon  xcatflowrequest <server> 3001
  logger -t xCAT -p local4.info "remoteshell: sending xcatflowrequest $master 3001"
  /$xcatpost/xcatflowrequest $master 3001
  rc=$? 
  logger -t xCAT -p local4.info "remoteshell:xcatflowrequest return=$rc" 
  if [ $rc -ne 0 ]; then
    logger -t xCAT -p local4.info "remoteshell: error from xcatflowrequest, will not use flow control"
    useflowcontrol=0
  fi
 fi
  getcredentials.awk $rootsshpvtkey | grep -E -v '</{0,1}xcatresponse>|</{0,1}serverdone>'|sed -e 's/&lt;/</' -e 's/&gt;/>/' -e 's/&amp;/&/' -e 's/&quot/"/' -e "s/&apos;/'/" > /tmp/ssh_root_key

  logger -t xCAT -p local4.info "remoteshell: gathering $rootsshpvtkey "
  #check whether the message is an error or not
  grep -E '<error>' /tmp/ssh_root_key
  if [ $? -ne 0 ]; then
	#The message contains the data we request
        cat /tmp/ssh_root_key | grep -E -v '</{0,1}errorcode>|/{0,1}data>|</{0,1}content>|</{0,1}desc>' > /root/.ssh/id_rsa
	logger -t xCAT -p local4.info ssh_root_key
	MYCONT=`cat /root/.ssh/id_rsa`
   MAX_RETRIES=10
   RETRY=0
	while [ -z "$MYCONT" ]; do
                if [ $useflowcontrol = "0" ]; then
                 let SLI=$RANDOM%10
                 let SLI=SLI+10
                 sleep $SLI
                fi
                RETRY=$(($RETRY+1))
                if [ $RETRY -eq $MAX_RETRIES ]
                then
                  break
                fi
                if [ $useflowcontrol = "1" ]; then
                  #first contact daemon  xcatflowrequest <server> 3001
                  logger -t xCAT -p local4.info "remoteshell: sending xcatflowrequest $master 3001"
                  /$xcatpost/xcatflowrequest $master 3001
                  rc=$? 
                  logger -t xCAT -p local4.info "remoteshell:xcatflowrequest return=$rc" 
                  if [ $rc -ne 0 ]; then
                     logger -t xCAT -p local4.info "remoteshell: error from xcatflowrequest, will not use flow control"
                     useflowcontrol=0
                  fi
                fi
		          getcredentials.awk $rootsshpvtkey | grep -v '<'|sed -e 's/&lt;/</' -e 's/&gt;/>/' -e 's/&amp;/&/' -e 's/&quot/"/' -e "s/&apos;/'/" > /root/.ssh/id_rsa
		          MYCONT=`cat /root/.ssh/id_rsa`
	done
  else
	#This is an error message
	ERR_MSG=`sed -n 's%.*<error>\(.*\)</error>.*%\1%p' /tmp/ssh_root_key`
	logger -t xCAT -p local4.err $rootsshpvtkey Error: $ERR_MSG
  fi
  rm /tmp/ssh_root_key

  if ! grep "PRIVATE KEY" /root/.ssh/id_rsa > /dev/null 2>&1 ; then
     rm /root/.ssh/id_rsa
  fi
  # if public key does not exist then generate one from the private key
  if [ ! -f /root/.ssh/id_rsa.pub ]; then
    if [ -r /root/.ssh/id_rsa ]; then
     ssh-keygen -y -f /root/.ssh/id_rsa > /root/.ssh/id_rsa.pub
     logger -t xCAT -p local4.err  remoteshell:transfer of the id_rsa.pub key failed. Had to generate a public key. 
    fi
  fi
fi

# start up the sshd for syncfiles postscript to do the sync work
logger -t xCAT -p local4.info "start up sshd"

if [[ $OSVER == ubuntu* || $OSVER == debian* ]]
then
    if [ ! -d /var/run/sshd ]
    then
	mkdir /var/run/sshd
	chmod 0755 /var/run/sshd
	/usr/sbin/sshd -f /etc/ssh/sshd_config
    else
	#service ssh restart
        restartservice ssh
    fi
else
    #service sshd restart
    # sshd is not enabled on SLES 12 by default
    # does not hurt anything to re-enable if it is enabled already
    enableservice sshd
    restartservice sshd
fi

kill -9 $CREDPID