#!/bin/bash -e

# put the SSH privkey in a predictable location
mkdir -pv $(dirname $ANSIBLE_PRIVATE_KEY_FILE_LOC)

# Remove existing key on restart, if present
[[ -f $ANSIBLE_PRIVATE_KEY_FILE_LOC ]] && rm -f $ANSIBLE_PRIVATE_KEY_FILE_LOC

# Insert the SSH key into the filesystem upon startup so it's not stored in the docker image
if [ "${ANSIBLE_SSH_ID_RSA}x" = "x" ]; then
  REGION=${AWS_REGION:='us-east-1'}
  # if not injected, pull from aws
  echo "Pulling ssh-id-rsa from aws region=${REGION}"
  aws secretsmanager get-secret-value --secret-id ssh-id-rsa --region ${REGION} \
      --query SecretString --output text > $ANSIBLE_PRIVATE_KEY_FILE_LOC
else
  # use the injected key
  echo "Using provided ssh-id-rsa key"
  echo "$ANSIBLE_SSH_ID_RSA" >| $ANSIBLE_PRIVATE_KEY_FILE_LOC
fi

[[ -s $ANSIBLE_PRIVATE_KEY_FILE_LOC ]] || {
  echo "ERROR: failed to set ANSIBLE_PRIVATE_KEY_FILE_LOC"
  exit 1
}
chmod -c 0400 $ANSIBLE_PRIVATE_KEY_FILE_LOC

java -jar sds-${VERSION}-SNAPSHOT.jar ${JAVA_OPTS:-} 2>&1
