#!/bin/bash
set -e

usage() {
  echo -e "${0##*/} -o origin.serv.er -d destinat.ion [-r new-app.name.destinat.ion] app.name.serv.er"
  exit 1
}

while getopts "o:d:a:r:h" arg; do
  case $arg in
    o) ORIGIN="$OPTARG" ;;
    d) DESTINATION="${OPTARG}" ;;
    r) RENAME="${OPTARG}" ;;
    h) usage ;;
  esac
done
let OPTIND--; shift ${OPTIND}

APP="$1"
# don't rename by default
RENAME="${RENAME:-${APP}}"

# required arguments
test -n "${ORIGIN}" || usage
test -n "${DESTINATION}" || usage
test -n "${APP}" || usage
test -n "${RENAME}"

# undeploy
abra app undeploy ${APP}

# ssh-agent
WITH_AGENT=false
if test -z "${SSH_AUTH_SOCK}"; then
  eval "$(ssh-agent)"
  WITH_AGENT=true
fi

ssh-add -l &>/dev/null || ssh-add

# find volumes and copy them to new server
abra app volume ls -n ${APP} | tail -n +4 | head -n -1 | cut -d "|" -f2 | while read volume; do
  ssh -A -o StrictHostKeyChecking=accept-new ${ORIGIN} rsync -avHAX /var/lib/docker/volumes/${volume}/ ${DESTINATION}:/var/lib/docker/volumes/${volume}/
done

# copy env file
cp -a ~/.abra/servers/${ORIGIN}/${APP}.env ~/.abra/servers/${DESTINATION}/${RENAME}.env

# TODO: copy secrets

# remove local ssh-agent. weird logic to cope with set -e
test ! ${WITH_AGENT} || ssh-agent -k