#!/bin/bash
# This script is used for both local testing and automated build process (CodeBuild)
set -e

# Local name of docker image to build and use
export IMAGE_NAME=temporary/hugo-ubuntu:latest

function usage {
    cat <<HELP_USAGE
    usage: $0 [-hd] [-s bucket]
    -d --develop      Run Hugo in interactive development mode
                      (asciidoc images will show broken)
    -s --sync=bucket  S3 bucket name to sync generate content
    -v --validate     Run validation on content
    -h --help         display help
HELP_USAGE
}

function build_docker_image {
    if ! [[ $(docker images -q $IMAGE_NAME) ]]; then
        echo "********** Building container image for Hugo and dependencies"
        docker build -t $IMAGE_NAME --build-arg GOPROXY=$(go env GOPROXY) .
    fi
}

function hugo_build {
    echo "********** Building site content"

    # Empty public folder completely
    shopt -s dotglob
    rm -rf hugo/public/*
    shopt -u dotglob

    build_docker_image

    # Generate full content
    docker run --rm -v "$PWD/hugo:/hugo-project" $IMAGE_NAME hugo
}

function hugo_validate {
    echo "********** Validating content"
    # Test HTML local and external links
    # Start hugo locally, reference //host.docker.internal for other containers to use
    docker run -d --name hugo_checker --rm -p 1313:1313 -v "$PWD/hugo:/hugo-project" temporary/hugo-ubuntu:latest hugo server --bind 0.0.0.0 -b http://localhost:1313/ 1>/dev/null

    # Wait until the web server is up
    while [ "`docker inspect -f {{.State.Health.Status}} hugo_checker`" != "healthy" ]; do sleep 0.5; done

    # Check all links
    # unset shell exit to stop the container above before exiting
    set +e
    # The validation muffet is only in Dockerhub - set credentials for CI/CD
    if ! [[ -z $DOCKERHUB_USERNAME || -z $DOCKERHUB_PASSWORD ]]; then
    echo "********** Docker credentials found, authenticating to hub.docker.com"
        echo $DOCKERHUB_PASSWORD | docker login -u $DOCKERHUB_USERNAME --password-stdin
    fi
    # Run for every translated language
    if ! uri_path_validate "en" ||
       ! uri_path_validate "zh" ||
       ! uri_path_validate "fr"; then
        echo "********** Validation errors, stopping local Hugo instance"
        docker stop hugo_checker 1>/dev/null
        echo "Link checks failed, exiting"
        exit 1
    fi
    set -e
    echo "********** Validation completed successfully, stopping local Hugo instance"
    docker stop hugo_checker 1>/dev/null
}

function uri_path_validate {
    # Run link checker for specific URI
    # Note - run the container on the host network to access Hugo running in a separate container
    #      - Exclude on github.com/aws in case of editURL changes. Will catch during automation
    echo "********** Running link checks on language: $1"
    if ! docker run --rm --net="host" raviqqe/muffet \
            --exclude="https://github.com/aws/" \
            --buffer-size="8192"  \
            --header="User-Agent: IotAtlasBot/1.0 (+http://iotatlas.net/en/bot/)" \
            --max-connections=512 --max-connections-per-host=2 --rate-limit=16 \
            http://localhost:1313/$1/; then
        echo "********** $1: Invalid links (see above)"
        return 1   # 1 = failure
    fi
    echo "********** $1: All links are valid"
}

function sync_s3 {
    echo "********** Synching content to S3 bucket: $BUCKET"
    aws s3 rm s3://$BUCKET --recursive
    aws s3 sync hugo/public s3://$BUCKET
}

function hugo_develop {
    build_docker_image
    echo "********** Starting Hugo for local development"
    docker run --rm -p 1313:1313 -v "$PWD/hugo:/hugo-project" $IMAGE_NAME
    exit 0
}

# Process arguments

for i in "$@"
do
case $i in
    -d|--develop)
    hugo_develop
    # Function exits - when in develop, not other tasks
    ;;
    -s=*|--sync=*)
    BUCKET="${i#*=}"
    shift # past arg=param
    ;;
    -v|--validate)
    VALIDATE=YES
    shift
    ;;
    -h|--help)
    usage
    exit
    ;;
    *)
    usage
    exit 1
    ;;
esac
done

# Build and optionally validate and sync
hugo_build

if [[ $VALIDATE ]]; then
    hugo_validate
fi

if [[ $BUCKET ]]; then
    sync_s3
fi
