#!/usr/bin/env bash

set -x
set -e

DIR_PATH=$(dirname $0)

$DIR_PATH/update

trap_with_arg() { # from https://stackoverflow.com/a/2183063/804678
  local func="$1"; shift
  for sig in "$@"; do
    trap "$func $sig" "$sig"
  done
}

stop() {
  trap - SIGINT EXIT
  printf '\n%s\n' "received $1, killing child processes"
  kill -s SIGINT 0
}

trap_with_arg 'stop' EXIT SIGINT SIGTERM SIGHUP

CLUSTER_COOKIE=`openssl rand -hex 8`

PORT=4002 elixir --sname two   --cookie $CLUSTER_COOKIE -S mix phx.server 2>/dev/null &
PORT=4003 elixir --sname three --cookie $CLUSTER_COOKIE -S mix phx.server 2>/dev/null &
PORT=4004 elixir --sname four  --cookie $CLUSTER_COOKIE -S mix phx.server 2>/dev/null &

$DIR_PATH/proxy &

PORT=4001 iex    --sname one --cookie $CLUSTER_COOKIE -S mix phx.server
