#! /bin/bash
set -e

# Must be run from the root moonbase application directory

function color {
  tput bold
  tput setaf $1
  shift
  echo $@
  tput sgr0
}
function red {
  color 1 $@
}
function green {
  color 2 $@
}
function yellow {
  color 3 $@
}
function blue {
  color 4 $@
}

function pushdir {
  pushd $@ > /dev/null
}
function popdir {
  popd > /dev/null
}

echo "😀 Setting up Moonbase… "

echo -n "🤔  Checking if $(blue -n localhost.appeals.twitch.tv) is configured… "
if hostess has localhost.appeals.twitch.tv > /dev/null 2>&1; then
  green 'yes, configured'
else
  red 'not found'
  yellow 'Setting localhost.appeals.twitch.tv in /etc/hosts (this will require root access)… '
  sudo hostess add localhost.appeals.twitch.tv 127.0.0.1
  green 'done'
fi

echo -n "🤔  Checking if $(blue -n localgql.appeals.twitch.tv) is configured… "
if hostess has localgql.appeals.twitch.tv > /dev/null 2>&1; then
  green 'yes, configured'
else
  red 'not found'
  yellow 'Setting localgql.appeals.twitch.tv in /etc/hosts (this will require root access)… '
  sudo hostess add localgql.appeals.twitch.tv 127.0.0.1
  green 'done'
fi

echo -n "🤔  Checking if $(blue -n moonbase cert) is in keychain… "
if security find-certificate -c tv.twitch.appeals.localhost /Library/Keychains/System.keychain > /dev/null 2>&1; then
  green 'found'
else
  red 'not found'
  yellow 'creating… '
  pushdir proxy
  sh addCert
  popdir
  green 'done'
fi

echo -n "🤔  Checking if $(blue -n proxy container image) is built… "
if docker image inspect moonbase-proxy > /dev/null 2>&1; then
  green 'found'
else
  red 'not found'
  yellow 'creating… '
  yarn proxy:build
  green 'done'
fi
