#!/bin/bash

set -e

ARGS=$@

WITH_DOWNTIME=

if [ ! -e 'klue-config.yaml' ]; then
    echo "ERROR: no klue-config.yaml in current dir"
    exit 1
fi

NAME=$(klue_config --name)
DOCKER_ROOT_REPO=$(klue_config --docker-repo)
AWS_PROFILE=$(klue_config --aws-user)
DOCKER_REPO=$DOCKER_ROOT_REPO/$NAME
DOCKER_BUCKET=$(klue_config --docker-bucket)

# . env_setup

usage() {
    cat << EOF
USAGE: $0 <options>

Build this project. Exit upon error.
- run local tests
- build a docker image
- start image in a container
- run tests against it
- push image to amazon EB

OPTIONS:

  --debug:          be very verbose.
  --test:           only run local tests.
  --push:           do push image to docker hub.
  --deploy:         do deploy to aws EB.
  --no-build:       skip building and testing the container.
  --with-downtime:  deploy with downtime (see eb_deploy).

EXAMPLES:

# test, build, push, deploy
./build.sh --push --deploy

# only push
./build.sh --no-build --push

# only deploy
./build.sh --no-build --deploy

EOF
}

do_check_git_repo() {
    IS_DIRTY_CLONE=$(git status --short --porcelain | wc -l)
    if [ "$IS_DIRTY_CLONE" -gt 0 ]; then
        echo "ERROR: $PWD is not clean! Commit and re-run."
        exit 1
    fi

    GIT_DIFF_REMOTE=$(git diff master origin/master | wc -l)
    if [ "$GIT_DIFF_REMOTE" -ne 0 ]; then
        echo "ERROR: $PWD differs from origin. Please push to origin before releasing!"
        exit 1
    fi
}

do_gen_version() {
    VERSION=$(print_version)
    echo "=> Using version: ${VERSION}"
}

do_get_last_version() {
    VERSION=$(docker images | grep $DOCKER_REPO | head -n 1 | awk '{ print $2 }')
    if [ -z "$VERSION" ]; then
        echo "ERROR: cannot find the latest docker image"
        exit 1
    fi
    echo "=> Using version: ${VERSION}"
}

do_unit_tests() {
    if [ -d 'test' ]; then
        echo "=> Running nosetests"
        nosetests -xv test/
    fi
}

do_push_to_registry() {
    # NOTE: for this to work, the running user must have logged in into the
    # docker hub using 'docker login'
    set +e
    IS_LOGGEDIN=$(docker info | grep Username)
    set -e
    if [ -z "$IS_LOGGEDIN" ]; then
        echo "ERROR: please login to docker hub with 'docker login'"
        exit 1
    fi

    echo "=> Pushing to registry ${DOCKER_REPO}:${VERSION}"
    docker push ${DOCKER_REPO}:${VERSION}
}

DO_PUSH=
DO_DEPLOY=
DONT_BUILD=
WITH_DEBUG=

parse_args() {
    while [ "$1" != "" ]; do
        case $1 in
            "--debug")         set -x; DEBUG='true'; WITH_DEBUG="--debug";;
            "--no-build")      export DONT_BUILD=1;;
            "--push")          export DO_PUSH=1;;
            "--deploy")        export DO_DEPLOY=1;;
            "--with-downtime") export WITH_DOWNTIME="--with-downtime";;
            "-h" | "--help")   usage; exit 0;;
            *)                 echo "Unknown argument '$1' (-h for help)"; exit 0;;
        esac
        shift
    done
}

parse_args $ARGS

do_check_git_repo

if [ -z "$DONT_BUILD" ]; then
    do_gen_version $WITH_DEBUG
    do_unit_tests $WITH_DEBUG
    build_docker_image $DOCKER_REPO $VERSION $WITH_DEBUG

    IMAGE_ID=$(docker images --quiet ${DOCKER_REPO}:${VERSION})
    run_acceptance_tests --image $IMAGE_ID
else
    do_get_last_version $WITH_DEBUG
fi

if [ ! -z "$DO_PUSH" ]; then
    do_push_to_registry $WITH_DEBUG
fi
if [ ! -z "$DO_DEPLOY" ]; then
    eb_deploy $WITH_DOWNTIME $VERSION $WITH_DEBUG

    echo "=> Waiting 1 min for cname swap to propagate"
    sleep 60

    run_acceptance_tests --live $WITH_DEBUG
fi

echo "=> Done."
