#!/bin/bash

set -e

TTY=""
if [[ ! -t 1 ]]; then
  TTY="-T"
fi

function task:bash {
  task:exec bash "${@}"
}

function task:ci:build {
  docker-compose build php
  docker-compose push php
}

function task:ci:test {
  task:lint:dockerfile
}

function task:exec {
  # Run any command in the php container.
  docker-compose exec php "${@}"
}

function task:composer {
  # Execute Composer commands.
  task:exec composer "${@}"
}

function task:db:export {
  task:drush sql:dump \
    --gzip \
    --result-file=/app/drupal.sql
}

function task:drupal:install {
  # Install Drupal.
  task:drush site:install -y --account-pass admin123 --existing-config
}

function task:drush {
  # Execute Drush commands.
  task:exec drush "${@}"
}

function task:frontend:console {
  docker-compose run --rm node
}

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

  # Only show functions that have the "task:" prefix.
  compgen -A function | sed -En 's/task:(.*)/\1/p' | cat -n

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

function task:lint:dockerfile {
  docker container run --rm -i \
    -v $(pwd)/.hadolint.yaml:/.config/hadolint.yaml \
    hadolint/hadolint hadolint \
    --ignore DL3008 \
    --ignore DL3022 \
    "${@}" - < tools/docker/Dockerfile
}

function task:test:functional {
  run-tests --testsuite functional "${@}"
}

function task:test:integration {
  # Run integration tests.
  run-tests --testsuite kernel "${@}"
}

function task:test:quality {
  # Run quality checks (code linting, static analysis, etc.).
  docker-compose run --no-deps php phpcs
  docker-compose run --no-deps php phpstan "--memory-limit=256M"
}

function task:test:unit {
  # Run unit tests.
  run-tests --testsuite unit "${@}"
}

function run-tests {
  # Run PHPUnit tests.
  docker-compose run php --user ${DOCKER_WEB_USER} php phpunit "${@}"
}

eval "task:${@:-help}"