#!/usr/bin/env sh

set -e

SSH_DEPLOY_TARGET=$2
SSH_DEPLOY_TARGET="${SSH_DEPLOY_TARGET:-"missingtarget"}"

SSH_PRIVATE_KEY=$3
SSH_PRIVATE_KEY="${SSH_PRIVATE_KEY:-"missingkey"}"

GOTO_FAIL=false

if [ "$SSH_DEPLOY_TARGET" = "missingtarget" ]; then
  echo "SSH target for web deployment job is unset!"
  GOTO_FAIL=true
fi

if [ "$SSH_PRIVATE_KEY" = "missingkey" ]; then
  echo "SSH key for web deployment job is unset!"
  GOTO_FAIL=true
fi

if [ "$GOTO_FAIL" = true ]; then
  return 1  
fi


TARGET_COMPONENTS=$(echo "$SSH_DEPLOY_TARGET" | tr '@' "\n")
TARGET_COMPONENTS=$(echo "$TARGET_COMPONENTS" | tr ':' "\n")

SSH_DEPLOY_TARGET_USER=$(echo "$TARGET_COMPONENTS" |  head -n 1 | tail -n 1)
SSH_DEPLOY_TARGET_HOST=$(echo "$TARGET_COMPONENTS" |  head -n 2 | tail -n 1)
SSH_DEPLOY_TARGET_PATH=$(echo "$TARGET_COMPONENTS" |  head -n 3 | tail -n 1)

SSH_DEPLOY_TARGET_USER="${SSH_DEPLOY_TARGET_USER:-"missinguser"}"
SSH_DEPLOY_TARGET_HOST="${SSH_DEPLOY_TARGET_HOST:-"missinghost"}"
SSH_DEPLOY_TARGET_PATH="${SSH_DEPLOY_TARGET_PATH:-"missingpath"}"

## Add the SSH key stored in SSH_PRIVATE_KEY variable to the agent store
## We're using tr to fix line endings which makes ed25519 keys work
## without extra base64 encoding.
## https://gitlab.com/gitlab-examples/ssh-private-key/issues/1#note_48526556
##
mkdir -p ~/.ssh
chmod 700 ~/.ssh
eval `ssh-agent -s`
echo "$SSH_PRIVATE_KEY" | base64 -d | tr -d '\r' | ssh-add -

## Use ssh-keyscan to scan the keys of your private server. 
## You can copy and repeat that command if you have more than 
## one server to connect to.
ssh-keyscan $SSH_DEPLOY_TARGET_HOST >> ~/.ssh/known_hosts
chmod 644 ~/.ssh/known_hosts

web() {
  scp www.zip "$SSH_DEPLOY_TARGET"
  ssh "$SSH_DEPLOY_TARGET_USER@$SSH_DEPLOY_TARGET_HOST" "cd $SSH_DEPLOY_TARGET_PATH && unzip -o www.zip && rm -f www.zip"
}

apk() {
  scp app/android/app/build/outputs/apk/release/app-release.apk "$SSH_DEPLOY_TARGET"
}

if declare -f "$1" > /dev/null
then
  "$@"
else
  echo "'$1' is not a known function name"
  exit 1
fi
