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

SELF=$(which $0); APP="$1"; TARGET="$2"; FORWARDED_PORT="$3"
REMOTE="dokku@$TARGET"
REPO="test-$(basename $APP)-$RANDOM"

destroy_app(){
  echo $REPO | ssh $REMOTE apps:destroy $REPO
}

failed(){
  echo "************ $1 failed ************"
  dokku logs $REPO
  destroy_app
  exit 1
}

TMP=$(mktemp -d -t "$TARGET.XXXXX")
rmdir $TMP && cp -r "$(dirname "$SELF")"/$APP $TMP
cd $TMP
git init
git config user.email "robot@example.com"
git config user.name "Test Robot"
git remote add target $REMOTE:$REPO

[[ -f gitignore ]] && mv gitignore .gitignore
git add .

[[ -x pre-commit ]] && ./pre-commit $REMOTE $REPO
git commit -m 'initial commit'
git push target master || failed git-push
if [[ -x post-deploy ]]; then
  ./post-deploy $REMOTE $REPO || failed post-deploy
fi

URL=$(dokku url $REPO)$FORWARDED_PORT
sleep 2
if (./check_deploy $URL); then
  echo "-----> Deploy success!"
else
  sleep 4
  if (./check_deploy $URL); then
    echo "-----> Deploy success!"
  else
    failed check-deploy
  fi
fi

dokku logs $REPO
destroy_app
