#!/bin/sh

# exit on error
set -e

DIR="$(cd "$(dirname "$0")" && pwd)"

cd "$DIR"

# fix warning when run on apple silicone
# https://stackoverflow.com/a/71594540/516629
export DOCKER_DEFAULT_PLATFORM=linux/amd64

# pull to ensure local machine has latest images
docker compose pull

# build and start containers in background
docker compose up --remove-orphans --detach --build

# Run logging if SONGWHIP_API_LOGFILE or$SONGWHIP_API_LOGS is set
if [ -n "$SONGWHIP_API_LOGFILE" ] || [ -n "$SONGWHIP_API_LOGS" ]; then
  if [ -n "$SONGWHIP_API_LOGFILE" ]; then
    # Create and empty the log file first
    : > "$SONGWHIP_API_LOGFILE"
  fi

  if [ -n "$SONGWHIP_API_LOGS" ] && [ -n "$SONGWHIP_API_LOGFILE" ]; then
    # Send logs to both the log file and stdout
    docker compose logs -f api | tee "$SONGWHIP_API_LOGFILE" 2>&1 &
  elif [ -n "$SONGWHIP_API_LOGS" ]; then
    # Send logs only to stdout
    docker compose logs -f api 2>&1 &
  elif [ -n "$SONGWHIP_API_LOGFILE" ]; then
    # Send logs only to the log file
    docker compose logs -f api > "$SONGWHIP_API_LOGFILE" 2>&1 &
  fi
fi

# docker-compose run api sh
docker compose run api sh ./migrations/scripts/up.sh 2>/dev/null
