#!/usr/bin/env bash

if [[ -z $(which parallel) || -z $(which tmux) || -z $(which gdate) ]]; then
  echo "Either 'parallel' or 'tmux' is not installed..."
  if [[ -z $(which brew) ]]; then
    echo "Homebrew is NOT installed. Homebrew needs to be installed to proceed."
    echo "Visit https://https://brew.sh/ for more information."
    exit 1
  else
    echo "Attempting to install parallel, tmux, coreutils..."
    brew install parallel tmux coreutils
  fi
fi

if [[ -z $1 ]]; then
  echo
  echo "Usage: $0 <env> [Deploy message]"
  echo
  echo
  exit 1
fi

ENV=$1
shift

if [[ $ENV == 'test' || $ENV == 'live' ]]; then
  if [[ -z $1 ]]; then
    while [[ -z $DEPLOY_MSG ]]; do
      echo
      read -p "Enter deployment message: " DEPLOY_MSG
      echo
    done
  else
    DEPLOY_MSG=$@
  fi
fi

NOW=$(date +%Y%m%d_%H%M)
LOG_DIR="deploy-$ENV-$NOW"
mkdir $LOG_DIR
echo "LOG_DIR: $LOG_DIR"

terminus org:site:list ohio-state-arts-and-sciences --upstream=ed613ce0-9d0a-4121-b9da-9e71f5995e85 --tag=D10 --fields=name --format=string | sort | tee $LOG_DIR/site_list.txt

parallel --delay 0.2 --tmuxpane --fg -j 36 -a $LOG_DIR/site_list.txt "scripts/deploy-site-env.sh {}.$ENV $DEPLOY_MSG 2>&1 | tee $LOG_DIR/{}.log"

echo
echo
echo "Sleeping for 11 seconds..."
echo
echo
sleep 11

reset

# wait;

cd $LOG_DIR
wc -l * | sort -n | tee line-counts.txt

MERGE_ERR=$(grep -rnw './' -e "Merge conflict")
if [[ -n ${MERGE_ERR} ]]; then
  echo
  echo "It looks there were some errors. Review _merge-conflicts.txt for more information."
  echo
  echo "$MERGE_ERR" >./_merge-conflicts.txt
else
  echo
  echo "No automatic merge issues detected. Success?"
  echo
fi
cd ..

echo
echo
echo "Sleeping for 11 more seconds..."
echo
echo
sleep 11
