#!/bin/sh


RSYSTEM2="" #empty
RUSER2="" #empty

#################################################################
## Functions


#######################################################
#
# MAIN
#
#######################################################
# import common variable and functions
. /opt/rcon/bin/sshr-base

cutLog
tracef "== Start of execution (sshr-generate) [$(/bin/date)] =="
PARAM="$@"
tracef "parameters=\"$PARAM\""

#disabled on sles15
tracef "SLES15 - nothing to do."
tracef "== End of execution (sshr-generate) [$(/bin/date)] (err=$RES) =="
exit 0

while getopts "c:qu:" OPTION; do
    case $OPTION in
	c) RSYSTEM2=$OPTARG;;
        q) VERBOSE="no";;
	u) RUSER2=$OPTARG;;
    esac
done
shift $(($OPTIND - 1))


#Step1: Detect current system type
SYSTEMTYPE=$(detectSystem)

#Step2: Detect remote system type
RSYSTEM=$(getRSystem $SYSTEMTYPE "$RSYSTEM2")
RC=$?
if [ $RC -ne 0 ];then
  tracef "ERROR:unable to identify remote system in paramtable"
  exit 209 
fi

#Step3: Detect if new key pair is required
CHECKKEYS=$(checkKeys)
if [ $CHECKKEYS -ne 0 ]; then
  #Remove old key pair
  rm -rf $PRIVATE_KEYP
  rm -rf $PUBLIC_KEYP
  #Generate new key pair
  ssh-keygen -q -b 2048 -f $PRIVATE_KEYP -C sshr_$SYSTEMTYPE -t rsa -N ""
  if [ $? -ne 0 ]; then
    tracef "ERROR:unable to generate key pair (err=$RES)"
    exit $RES 
  fi
  #Generate file with sha1sum of keys
  SSHA1=$(sha1sum $PRIVATE_KEYP 2>/dev/null | cut -f 1 -d " ")
  SSHA2=$(sha1sum $PUBLIC_KEYP 2>/dev/null | cut -f 1 -d " ")

  rm $KEY_CONFIG 2>/dev/null
  echo $SSHA1 >> $KEY_CONFIG
  echo $SSHA2 >> $KEY_CONFIG

  #Change access rights for file with public key
  id -g unity >/dev/null 2>&1
  if [ $? -eq 0 ];then
    chown root:unity $PUBLIC_KEYP
    chmod 640 $PUBLIC_KEYP
    chown root:unity $KEY_CONFIG
    chmod 640 $KEY_CONFIG
  else
    chmod 644 $PUBLIC_KEYP
    chmod 644 $KEY_CONFIG
  fi
else
  tracef "key pair will be reused"
fi



  #Step5: Get IP address of remote system and store it to $SERVERIP
  SERVERIP=$(/opt/rcon/bin/getremintIP -c $RSYSTEM 2>/dev/null)
  RC=$?
  tracef "param:remote IP=\"$SERVERIP\" (res=$RC)"

  #Step6: Get path to public directory to store public key to be accessible via HTTP
  PUBLIC_DIR=$(getValue $SYSTEMTYPE fpath)

  #Step7: Get accessible directory on remote system
  HTTP_DIR=$(getValue $RSYSTEM wpath)

  #Step8: Remove key from know_hosts, sometimes this record is changed
  if [ -n "$RUSER2" ];then
    USER_NAME="$RUSER2"
  else
    USER_NAME=$(getValue $RSYSTEM user)
  fi
  tracef "param:remote username=\"$USER_NAME\""

  #USER_HOME=$(getUserHome $USER_NAME)
  #Exception
  #if [ "$SYSTEMTYPE" == "assistant_intl" ];then
  #  #Special handling for engr/root feature on Assistant
  #  USER_HOME="/root"
  #fi
  #KH_DESTINATION="/root/.ssh/known_hosts"
  #grep -v $SERVERIP\  $KH_DESTINATION >/var/rcon/known_hosts 2>/dev/null
  #tracef "update known host file in \"$KH_DESTINATION\""
  #cp -f /var/rcon/known_hosts $KH_DESTINATION 2>/dev/null


  #Step9: Copy key to provide public key for remote host
  tracef "copy public key to provide it for remote host"
  tracef "command:cp -f $PUBLIC_KEYP $PUBLIC_DIR/$PUBLIC_KEY_STUB 2>/dev/null"
  cp -f $PUBLIC_KEYP $PUBLIC_DIR/$PUBLIC_KEY_STUB 2>/dev/null
  id -g unity >/dev/null 2>&1
  if [ $? -eq 0 ];then
    chown root:unity $PUBLIC_DIR/$PUBLIC_KEY_STUB
    chmod 640 $PUBLIC_DIR/$PUBLIC_KEY_STUB
  else 
    chmod 644 $PUBLIC_DIR/$PUBLIC_KEY_STUB
  fi

  #Workaround for key exchange with assistant
  if [ "$SYSTEMTYPE" == "assistant_intl" ];then
    PUBLIC_DIR="/opt/unity/htdocs/public"
    tracef "copy key to old path (PUBLIC_DIR=$PUBLIC_DIR)"
    tracef "command:cp -f $PUBLIC_KEYP $PUBLIC_DIR/$PUBLIC_KEY_STUB"
    cp -f $PUBLIC_KEYP $PUBLIC_DIR/$PUBLIC_KEY_STUB 2>/dev/null
  fi


  #Step10: Inform remote server to load new key (via curl)
  tracef "inform remote server to load new key"
  tracef "command:$CURL $CURL_PARAMS -o /var/rcon/dres$RSYSTEM.html \"http://$SERVERIP$HTTP_DIR/cgi-bin/$RECOVERY_SCRIPT?system=$SYSTEMTYPE&user=$USER_NAME\""
  $CURL $CURL_PARAMS -x "" -o "/var/rcon/dres$RSYSTEM.html" "http://$SERVERIP$HTTP_DIR/cgi-bin/$RECOVERY_SCRIPT?system=$SYSTEMTYPE&user=$USER_NAME" >/dev/null 2>&1
  RES=$?
  tracef "result from curl command = \"$RES\""

  LRES=$(grep RES "/var/rcon/dres$RSYSTEM.html" 2>/dev/null)
  CRES=$?
  tracef "result from HTTP distribution = \"$LRES\""
  tracef "check content = $CRES (OK=0)"
  #Workaround for HTTP -> HTTPS
  if [ $CRES -ne 0 ]; then
    if [ "$RSYSTEM" == "assistant_intl" ];then
      tracef "use HTTPS protocol to start distribution"
      tracef "command:$CURL $CURL_PARAMS -o /var/rcon/dres$RSYSTEM.html \"https://$SERVERIP$HTTP_DIR/cgi-bin/$RECOVERY_SCRIPT?system=$SYSTEMTYPE&user=$USER_NAME\""
      $CURL $CURL_PARAM -x "" -o "/var/rcon/dres$RSYSTEM.html" "https://$SERVERIP$HTTP_DIR/cgi-bin/$RECOVERY_SCRIPT?system=$SYSTEMTYPE&user=$USER_NAME" >/dev/null 2>&1

      RES=$?
      tracef "result from curl command=$RES"
      LRES=$(grep RES "/var/rcon/dres$RSYSTEM.html" 2>/dev/null)
      tracef "result from HTTP distribution=\"$LRES\""
    fi
  fi




  #Map error to Assistant's error code
  if [ "$RES" == "7" ];then
    RES="202"
  fi

  if [ $RES -eq 0 ]; then
    RES=`cat /var/rcon/dres$RSYSTEM.html 2>/dev/null| grep RES | awk '{print $2}'`
    tracef "result from distribution to remote system=\"$RES\""
    #[ -z "$RES" ] && RES=0
  fi
  
#Remove /var/rcon/dres$RSYSTEM.html
RUNASROOT=$(getRootAccess $SYSTEMTYPE)
$RUNASROOT rm -f "/var/rcon/dres$RSYSTEM.html" 2>/dev/null

#set +x
tracef "== End of execution (sshr-generate) [$(/bin/date)] (err=$RES) =="
tracef ""
tracef ""

exit $RES


