#!/bin/bash

CLIENT_USER=mnr17

cd $(dirname $0)

app_url="https://lets-draw.live?room=test-$(date +%s)"
client_hostnames=$(cat client-hostnames)
num_peers=$(echo $client_hostnames | wc -w)

install_pids=""
for hostname in $client_hostnames; do
  (
    ssh -oStrictHostKeyChecking=no $CLIENT_USER@$hostname "rm -rf ~/client" &&
    scp -r client $CLIENT_USER@$hostname:~/client &&
    ssh -oStrictHostKeyChecking=no $CLIENT_USER@$hostname "
      source ~/.nvm/nvm.sh &&
      cd ~/client &&
      export PUPPETEER_SKIP_CHROMIUM_DOWNLOAD=1 &&
      npm install
    "
  ) &
  install_pids="$install_pids $!"
  # The file system is shared between hosts in this case, so break after
  # installing once.
  break
done
wait $install_pids

current_peer_index=0
run_pids=""
for hostname in $client_hostnames; do
  ssh -oStrictHostKeyChecking=no $CLIENT_USER@$hostname "
    source ~/.nvm/nvm.sh &&
    cd ~/client &&
    export APP_URL=$app_url &&
    export PEER_INDEX=$current_peer_index &&
    export NUM_PEERS=$num_peers &&
    export PUPPETEER_EXECUTABLE_PATH=\"/opt/google/chrome/chrome\" &&
    node --experimental-modules spawn-peer.js
  " &
  run_pids="$run_pids $!"
  current_peer_index=$((current_peer_index+1))
done
wait $run_pids
