#!/bin/bash

set -e

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

function task:build-and-push-images {
  export DOCKER_BUILDKIT=1

  docker-compose build assets
  docker-compose push assets
}

function task:copy-theme-assets {
  docker container run --entrypoint sh --name oliverdavies-uk-assets oliverdavies-uk-assets
  docker cp oliverdavies-uk-assets:/node/build web/themes/custom/opdavies
  docker container rm oliverdavies-uk-assets
}

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

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

function task:ci:deploy {
  ansible-galaxy install -r tools/deployment/requirements.yml

  ansible-playbook tools/deployment/deploy.yml \
    -e "ansistrano_deploy_branch=${1:-production}" \
    -i tools/deployment/hosts.yml \
    --vault-password-file="${2:-tools/deployment/.vault-pass.txt}" \
    "${@}"
}

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

function task:exec {
  # Run any command in the php container.
  docker-compose exec $TTY 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}"