#!/usr/bin/env bash
set -eo pipefail

# Prefer app executables
app_root="$(
  cd "$(dirname "$0")/.."
  pwd
)"
export PATH="$app_root/bin:$PATH"

if [ -e tmp/saas.txt ]; then
  export SAAS=1
fi

if [ -n "$SAAS" ]; then
  export BUNDLE_GEMFILE="Gemfile.saas"
fi

# Install gum if needed
if ! command -v gum &>/dev/null; then
  echo
  echo "▸ Installing gum"
  if command -v pacman &>/dev/null; then
    sudo pacman -S --noconfirm gum
  elif command -v brew &>/dev/null; then
    brew install gum
  else
    echo "Please install gum: https://github.com/charmbracelet/gum"
    exit 1
  fi
  echo
fi

step() {
  local step_name="$1"
  shift

  gum style --foreground 135 --bold "▸ $step_name"
  gum style --foreground 240 "$*"

  "$@"

  local exit_code=$?
  echo
  return $exit_code
}

needs_seeding() {
  if [ "$CI" != "" ]; then
    return 1
  fi

  has_data=$(bin/rails runner "pp Account.all.any?" 2>/dev/null)
  if [ "$has_data" = "true" ] ; then
    return 1
  else
    return 0
  fi
}


setup_database() {
  local adapter="$1"
  local reset="$2"
  local label="${adapter:+ ($adapter)}"
  local env_cmd="${adapter:+env DATABASE_ADAPTER=$adapter}"

  # When setting up sqlite in SAAS mode, we need to disable SAAS so that
  # database.yml will use database.sqlite.yml instead of the fizzy-saas config.
  # We also unset BUNDLE_GEMFILE so the standard Gemfile is used (without fizzy-saas).
  if [ -n "$SAAS" ] && [ "$adapter" = "sqlite" ]; then
    env_cmd="env DATABASE_ADAPTER=$adapter SAAS=false BUNDLE_GEMFILE="
  fi

  if [ "$reset" = "true" ]; then
    step "Resetting the database$label" $env_cmd rails db:reset
  else
    step "Preparing the database$label" $env_cmd rails db:prepare

    if needs_seeding; then
      step "Seeding the database$label" $env_cmd rails db:seed
    fi
  fi
}

echo
gum style --foreground 153 "   ˚ ∘             ∘ ˚   "
gum style --foreground 111 --bold "  ∘˚˳°∘°  𝒻𝒾𝓏𝓏𝓎  °∘°˳˚∘  "
echo

step "Installing Ruby" mise install --yes
eval "$(mise hook-env)"

if which pacman >/dev/null 2>&1; then
  packages=(imagemagick mariadb-libs openslide libvips gitleaks)
  if ! pacman -Q "${packages[@]}" >/dev/null 2>&1; then
    step "Installing packages" sudo pacman -S --noconfirm --needed "${packages[@]}"
  fi
fi

# Ensure gh-signoff is installed and up to date
step "Set up gh-signoff" bash -c "gh extension install basecamp/gh-signoff || gh extension upgrade basecamp/gh-signoff"

bundle config set --local auto_install true
step "Installing RubyGems" bundle install

if [ -n "$SAAS" ]; then
  saas_setup=$(bundle show fizzy-saas)/bin/setup
  source "$saas_setup"
else
  if ! nc -z localhost 3306 2>/dev/null; then
    if docker ps -aq -f name=fizzy-mysql | grep -q .; then
      step "Starting MySQL" docker start fizzy-mysql
    else
      step "Setting up MySQL" bash -c '
        docker pull mysql:8.4
        docker run -d \
          --name fizzy-mysql \
          -e MYSQL_ALLOW_EMPTY_PASSWORD=yes \
          -p 3306:3306 \
          mysql:8.4
        echo "MySQL is starting… (it may take a few seconds)"
      '
    fi
  fi
fi

reset_flag=""
[[ $* == *--reset* ]] && reset_flag="true"

if [ -n "$SAAS" ]; then
  for adapter in saas sqlite; do
    setup_database "$adapter" "$reset_flag"
  done
else
  for adapter in sqlite mysql; do
    setup_database "$adapter" "$reset_flag"
  done
fi

step "Cleaning up logs and tempfiles" rails log:clear tmp:clear

gum style --foreground 46 "✓ Done (${SECONDS} sec)"
