#!/bin/bash

function run_site_only() {
    [ "$SITE_ONLY" == "true" ]
}

function run_override_only() {
    [ "$OVERRIDE_ONLY" == "true" ]
}


case "$1" in
    -)
        OVERRIDE_ONLY=true
        shift
        ;;
    --)
        SITE_ONLY=true
        shift
        ;;
esac

case "$1" in
    test)
        if [[ "$2" == "-s" || "$2" == "--run-selenium" ]]; then
            if ! type selenium &> /dev/null; then
                echo "Failed to run Selenium. It must not be installed or not accessible on \$PATH!"
                exit 1
            fi

            echo "Running Selenium..."
            selenium 2> /dev/null &
            sleep 3s
        fi

        # Test site
        stack test
        ;;
    gencss)
        shift
        stack exec gencss -- "$@"
        ;;
    # Override of hakyll site commands
    -h|--help)
        run_override_only || ! run_site_only && cat << EOF
Wraps hakyll's provided site tool to augment certain commands.

Usage:
  ./site [-|--] COMMAND

Available commands:
  build*
  clean*
  deploy*
  gencss
  test

Hakyll site commands:
  build
  check
  clean
  deploy
  preview
  rebuild
  server
  watch

Starred (*) commands indicate a overridden hakyll site command. However once the override is
run, the corresponding hakyll command is then run. This can be disabled with by specifying '--'
as the first argument, which will then pass all remaining arguments to the hakyll site command.
Similarily, to only run the override, specify '-' as the first argument.

For more details about hakyll site commands and options, see './site -- --help'.
EOF

        # Only run hakyll site --help command if override was not run
        run_override_only && exit

        # Only run hakyll site --help command if -- site only
        run_site_only && stack exec blog-rekahsoft-ca -- --help | sed 's/\(Usage: \)blog-rekahsoft-ca/\1.\/site -/g'
        ;;
    build)
        run_override_only || ! run_site_only && stack build
        run_override_only && exit $?
        ;;&
    clean)
        run_override_only || ! run_site_only && stack clean
        run_override_only && exit $?
        ;;&
    deploy)
        pushd infra > /dev/null

        # Only run hakyll site deploy command when site-only is given. Additionally, when
        # neither site-only or override-only are given, run only the override. The deploy
        # override uses terraform which is also setup to deploy the hakyll site static files
        run_override_only || ! run_site_only && (
            export PLAN=".plans/local-$(date +%F_%R).plan"
            [ ! -d .plans ] && mkdir .plans
            make plan deploy
            ) && exit $?

        run_site_only && export S3_BUCKET="$(terraform output s3_bucket_static)"

        popd > /dev/null
        ;;&
    *)
        stack exec blog-rekahsoft-ca -- "$@"
        ;;
esac
