#!/usr/bin/env bash

set -o errexit
set -o pipefail

DC="${DC:-exec}"

# If we're running in CI we need to disable TTY allocation for docker compose
# commands that enable it by default, such as exec and run.
TTY=""
if [[ ! -t 1 ]]; then
  TTY="-T"
fi

# -----------------------------------------------------------------------------
# Helper functions start with _ and aren't listed in this script's help menu.
# -----------------------------------------------------------------------------

function _dc {
  docker compose "${DC}" ${TTY} "${@}"
}

function _build_run_down {
  docker compose build
  docker compose run ${TTY} "${@}"
  docker compose down
}

# -----------------------------------------------------------------------------

function cmd {
  # Run any command you want in the web container
  _dc web "${@}"
}

function manage {
  # Run any manage.py commands

  # We need to collectstatic before we run our tests.
  if [ "${1-''}" == "test" ]; then
    cmd python3 manage.py collectstatic --no-input
  fi

  cmd python3 manage.py "${@}"
}

function lint:dockerfile {
  # Lint Dockerfile
  docker container run --rm -i \
    hadolint/hadolint hadolint --ignore DL3008 -t style "${@}" - < Dockerfile
}

function lint {
  # Lint Python code
  cmd flake8 "${@}"
}

function format:imports {
  # Sort Python imports
  cmd isort . "${@}"
}

function format {
  # Format Python code
  cmd black . "${@}"
}

function quality {
  # Perform all code quality commands together
  format:imports
  format
  lint
}

function secret {
  # Generate a random secret that can be used for your SECRET_KEY and more
  cmd python3 -c "from django.core.management.utils import get_random_secret_key; print(get_random_secret_key())"
}

function shell {
  # Start a shell session in the web container
  cmd bash "${@}"
}

function psql {
  # Connect to PostgreSQL
  # shellcheck disable=SC1091
  . .env
 _dc postgres psql -U "${POSTGRES_USER}" "${@}"
}

function redis-cli {
  # Connect to Redis
  _dc redis redis-cli "${@}"
}

function pip3:install {
  # Install pip3 dependencies and write lock file
  _build_run_down web bash -c "cd .. && bin/pip3-install"
}

function pip3:outdated {
  # List any installed packages that are outdated
  cmd pip3 list --outdated
}

function yarn:install {
  # Install yarn dependencies and write lock file
  _build_run_down js yarn install
}

function yarn:outdated {
  # List any installed packages that are outdated
  _dc js yarn outdated
}

function yarn:build:js {
  # Build JS assets, this is meant to be run from within the assets container
  mkdir -p ../public/js
  node esbuild.config.mjs
}

function yarn:build:css {
  # Build CSS assets, this is meant to be run from within the assets container
  local args=()

  if [ "${NODE_ENV:-}" == "production" ]; then
    args=(--minify)
  else
    args=(--watch)
  fi

  mkdir -p ../public/css
  DEBUG=0 tailwindcss --postcss -i css/app.css -o ../public/css/app.css "${args[@]}"
}

function clean {
  # Remove cache and other machine generates files
  rm -rf public/*.* public/admin public/js public/css public/images public/fonts \
    public_collected/*.* public_collected/admin public_collected/js \
    public_collected/css public_collected/images public_collected/fonts \
    .pytest_cache/ .coverage celerybeat-schedule

  touch public/.keep public_collected/.keep
}

function ci:install-deps {
  # Install Continuous Integration (CI) dependencies
  sudo apt-get install -y curl shellcheck
  sudo curl \
    -L https://raw.githubusercontent.com/nickjj/wait-until/v0.2.0/wait-until \
    -o /usr/local/bin/wait-until && sudo chmod +x /usr/local/bin/wait-until
}

function ci:test {
  # Execute Continuous Integration (CI) pipeline
  #
  # It's expected that your CI environment has these tools available:
  #   - https://github.com/koalaman/shellcheck
  #   - https://github.com/nickjj/wait-until
  shellcheck run bin/*
  lint:dockerfile "${@}"

  cp --no-clobber .env.example .env

  docker compose build
  docker compose up -d

  # shellcheck disable=SC1091
  . .env
  wait-until "docker compose exec -T \
    -e PGPASSWORD=${POSTGRES_PASSWORD} postgres \
    psql -U ${POSTGRES_USER} ${POSTGRES_USER} -c 'SELECT 1'"

  docker compose logs

  lint "${@}"
  format:imports --check
  format --check
  manage migrate
  manage test
}

function help {
  printf "%s <task> [args]\n\nTasks:\n" "${0}"

  compgen -A function | grep -v "^_" | cat -n

  printf "\nExtended help:\n  Each task has comments for general usage\n"
}

# This idea is heavily inspired by: https://github.com/adriancooney/Taskfile
TIMEFORMAT=$'\nTask completed in %3lR'
time "${@:-help}"
