#!/usr/bin/env bash
# shellcheck disable=SC2188

<<COMMENT
This script does all neccessary setup to run a docker image within EKS, then runs the server
or worker.

Called By: Our Deployment Helm Templates in provisioning/kubernetes/palolo-app/
           Our CMD in our Dockerfiles
COMMENT

set -euo pipefail

# Base setup.
cd "$(dirname $(dirname "$0") )"
scripts/docker_base_setup.sh

# The server and worker scripts load `.env` at runtime so there's no issue
# here like there is for the client.
cd packages/server

# Optionally run server or worker; default server.
PALOLO_COMMAND=${PALOLO_COMMAND:-server}
case $PALOLO_COMMAND in
  (backup)
    source .env

    # export PG* vars from .env
    export PGDATABASE=$DATABASE_NAME
    export PGHOST=$DATABASE_HOST
    export PGPASSWORD=$DATABASE_PASSWORD
    export PGPORT=$DATABASE_PORT
    export PGUSER=$DATABASE_USER

    exec pg_dump -Z 9 -v --exclude-table-data "public.Session" | aws s3 cp --storage-class STANDARD_IA --sse aws:kms - "s3://${DATABASE_ARCHIVE}/pg_dump_$(date +%s).sql.gz"

    # TODO - add error handling and slack notification on failure
    ;;
  (server|worker)
    exec node --import=tsx src/"${PALOLO_COMMAND}".ts
    ;; # OK
  (*) printf >&2 'Error, invalid command ${PALOLO_COMMAND}...\n'; exit 1;;
esac
