#!/bin/bash
BEARER_TOKEN="$1"
BASE_URL="$2"
LOGON_USER_HOME="$3"
SSH_DIR="$3/.ssh"
EXIT_CODE=0
#
curl_output=$( curl -H 'X-SAPSSE-Forward-Request-To: master' -H 'Authorization: Bearer '${BEARER_TOKEN} "${BASE_URL}/security/api/restsecurity/users_with_permission?permission=LANDSCAPE:MANAGE:AWS" 2>/dev/null )
curl_exit_code=$?
if [ "${curl_exit_code}" = "0" ]; then
  users=$( echo "${curl_output}" | jq -r '.[]' )
  jq_exit_code=$?
  if [ "${jq_exit_code}" = "0" ]; then
    logger -t sailing "Users with LANDSCAPE:MANAGE:AWS permission: ${users}"
    public_keys=$( for user in ${users}; do
      ssh_key_curl_output=$(curl -H 'X-SAPSSE-Forward-Request-To: master' -H 'Authorization: Bearer '${BEARER_TOKEN} "${BASE_URL}/landscape/api/landscape/get_ssh_keys_owned_by_user?username[]=${user}" 2>/dev/null )
      ssh_key_curl_exit_code=$?
      if [ "${ssh_key_curl_exit_code}" = "0" ]; then
        echo "${ssh_key_curl_output}" | jq -r '.[].publicKey'
    ssh_key_jq_exit_code=$?
    if [ "${ssh_key_jq_exit_code}" != "0" ]; then
      EXIT_CODE=${ssh_key_jq_exit_code}
      logger -t sailing "Couldn't parse response of get_ssh_keys_owned_by_user; jq exit code ${ssh_key_jq_exit_code}"
    fi
      else
        EXIT_CODE=${ssh_key_curl_exit_code}
    logger -t sailing "Couldn't get response of get_ssh_keys_owned_by_user; curl exit code ${ssh_key_corl_exit_code}"
      fi
    done | sort -u )
    logger -t sailing "Obtained public keys: ${public_keys}"
    if [ ! -f ${SSH_DIR}/authorized_keys.org ]; then
      # Create a copy of the original authorized_keys file as generated by AWS from the start-up key:
      logger -t sailing "Saving original authorized_keys file from ${SSH_DIR}"
      cp ${SSH_DIR}/authorized_keys ${SSH_DIR}/authorized_keys.org
    fi
    # Start out with the original AWS-generated authorized_keys file
    # and append the public SSH keys of all users having LANDSCAPE:MANAGE:AWS permission:
    echo "$( cat ${SSH_DIR}/authorized_keys.org )
${public_keys}" | sort -u >${SSH_DIR}/authorized_keys
  else
    EXIT_CODE=${jq_exit_code}
    logger -t sailing "Couldn't parse response of users_with_permission; jq exit code ${jq_exit_code}"
  fi
else
  EXIT_CODE=${curl_exit_code}
  logger -t sailing "Couldn't get response of users_with_permission; curl exit code ${curl_exit_code}"
fi
exit ${EXIT_CODE}
