#!/bin/sh

# File autogenerated by mix horizon.init (source: deploy.sh.eex)
#
# Calls `deploy_script-my_app.sh` on the target host.
# The deploy_script is expected to be on the local host.
# The script is located in the build folder for each `bin_path` and release.
#
# Examples
#
#    ./bin/deploy-my_app.sh -h host
#    ./bin/deploy-my_app.sh -h user@host
#    ./bin/deploy-my_app.sh -h user@host1,user@host2
#
#

set -eu

# Default deployment user and host
DEPLOY_HOSTS_SSH="<%= Enum.join(@deploy_hosts_ssh, ",") %>"
APP_PATH="<%= @app_path %>"
APP="<%= @app %>"

# Parse arguments
while getopts "u:h:" opt; do
  case $opt in
  h) DEPLOY_HOSTS_SSH=$OPTARG ;;
  *)
    echo "Usage: $0 [-h [user@]host]"
    exit 1
    ;;
  esac
done
shift $((OPTIND - 1))

if [ $# -gt 0 ]; then
  echo "Usage: $0 [-h [user@]host]"
  exit 1
fi

release=$(cat "<%= @releases_path %>/$APP.data")

GREEN='\033[0;32m'
RED='\033[0;31m'
RESET='\033[0m'

OLD_IFS="$IFS"
IFS=','

# Define the installation script and arguments
INSTALL_SCRIPT="<%= @bin_path %>/deploy_script-<%= @app %>.sh"
INSTALL_ARGS="$APP $APP_PATH $release"

for host in $DEPLOY_HOSTS_SSH; do
  scp "<%= @releases_path %>/$release" "${host}:/tmp/$APP.tar.gz"

  # Run the deploy script on the remote host
  ssh "${host}" "sh -s -- $INSTALL_ARGS" <"$INSTALL_SCRIPT"

  if [ $? -eq 0 ]; then
    printf "${GREEN}Deployment to ${host} successful.${RESET}\n"
  else
    printf "${RED}Deployment failed.${RESET}\n"
    exit 1
  fi
done
IFS="$OLD_IFS"
