#!/usr/bin/env bash
set -euo pipefail

SCRIPT_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)
TARGET=${DEPLOY_TARGET:-daniel@10.0.0.33}
SSH_KEY=${DEPLOY_SSH_KEY:-$HOME/.ssh/harbor_deploy}
artifact=${1:-}

if [[ -z "$artifact" ]]; then
  "$SCRIPT_DIR/build-release.sh"
  artifact=$(find "$SCRIPT_DIR/artifacts" -maxdepth 1 -type f -name 'harbor-*.tar.gz' -printf '%T@ %p\n' | sort -nr | cut -d' ' -f2- | sed -n '1p')
fi
test -f "$artifact"
test -f "$artifact.sha256"

name=$(basename "$artifact")
checksum=$(cut -d' ' -f1 "$artifact.sha256")
ssh_opts=(-i "$SSH_KEY" -o BatchMode=yes -o IdentitiesOnly=yes -o StrictHostKeyChecking=yes)

printf '%s\n' "uploading $name"
rsync -az --partial -e "ssh -i $SSH_KEY -o BatchMode=yes -o IdentitiesOnly=yes -o StrictHostKeyChecking=yes" "$artifact" "$TARGET:/opt/harbor/incoming/$name"
ssh "${ssh_opts[@]}" "$TARGET" sudo /opt/harbor/deploy/remote/activate-release.sh "/opt/harbor/incoming/$name" "$checksum"
ssh "${ssh_opts[@]}" "$TARGET" sudo /opt/harbor/deploy/remote/status.sh
