#!/bin/sh
set -eu
root=/srv/sentinel
if [ "${1:-}" = init ]; then
 mkdir -p "$root/shared/storage/app/private" "$root/shared/storage/framework/cache/data" "$root/shared/storage/framework/sessions" "$root/shared/storage/framework/views" "$root/shared/storage/logs" "$root/releases"
 if [ ! -e "$root/current" ]; then
  release="$root/releases/1.0.0-initial"
  mkdir -p "$release"
  cp -a /opt/source/. "$release/"
  rm -rf "$release/storage"
  ln -s "$root/shared/storage" "$release/storage"
  ln -s "$root/shared/.env" "$release/.env"
  ln -s "$release" "$root/current"
 fi
 if [ ! -f "$root/shared/.env" ]; then
  cp /opt/source/.env.example "$root/shared/.env"
  # Never print generated credentials. Retrieve the token from the shared env file.
  cd "$root/current"
  php artisan key:generate --force
  php /opt/source/docker/init-env.php
 fi
 chown -R www-data:www-data "$root"
 chmod 600 "$root/shared/.env"
 exit 0
fi
cd "$root/current"
case "${1:-web}" in
 web) exec php-fpm -F ;;
 worker|updates|scheduler)
  mode="$1"
  export WORKER_ROLE="$mode"
  while :; do
   cd "$root/current"
   if [ ! -f storage/app/installed.json ] || [ -f storage/app/deployment-maintenance ]; then sleep 3; continue; fi
   if [ "$mode" = scheduler ]; then php artisan schedule:run --no-interaction || true; sleep 1
   elif [ "$mode" = updates ]; then php artisan queue:work redis --queue=updates --tries=1 --timeout=1800 --max-time=30 --sleep=3 || true
   else php artisan queue:work redis --queue=monitoring --tries=3 --timeout=40 --max-time=60 --sleep=3 || true
   fi
   sleep 1
  done ;;
 *) exec "$@" ;;
esac
