#!/bin/bash
set -e

TARGET=$1

IMAGE="gitlab/gitlab-ee"
TAG_TEST="test"
TAG_PROD="prod"
TAG_PREV="old_prod"
SERVICE_TEST="docker-compose@gitlab_test.service"
SERVICE_PROD="docker-compose@gitlab_prod.service"
BACKUP_CMD="gitlab-backup create SKIP=repositories,builds,artifacts,lfs"

DOCKER="/usr/bin/docker"
AWK="/usr/bin/awk"
SYSTEMCTL="/usr/bin/systemctl"

compare_images(){
    id_1=$(${DOCKER} images -q "${IMAGE}:$1")
    id_2=$(${DOCKER} images -q "${IMAGE}:$2")
    [[ "x${id_1}" == "x${id_2}" ]]
    echo $?
}

case "${TARGET}" in
    check)
        ${DOCKER} pull ${IMAGE}:latest
	res=$(compare_images "latest" "${TAG_TEST}")
        echo "--------"
        if [[ $res -ne 0 ]]; then
            echo "updates available"
            exit 1
        fi
        echo "${IMAGE}:latest same as ${IMAGE}:${TAG_TEST}"
        ;;
    check_nagios)
	set +e
        ${DOCKER} pull -q ${IMAGE}:latest >/dev/null
        if [[ $? -ne 0 ]]; then
            echo "UPDATE CRITICAL: Could not pull ${IMAGE}:latest |"
	    exit 2
	fi
	res=$(compare_images "latest" "${TAG_TEST}")
        if [[ $res -ne 0 ]]; then
            echo "UPDATE WARNING: Update available |"
            exit 1
        fi
        echo "UPDATE OK: ${IMAGE}:{TAG_TEST} is same as latest |"
	;;
    latest_test)
        res=$(compare_images "latest" "${TAG_TEST}")
        if [[ $res -eq 0 ]]; then
            echo "already up to date"
            exit 1
        fi
        ${DOCKER} exec -t "gitlab_${TAG_TEST}" $BACKUP_CMD
        ${SYSTEMCTL} stop ${SERVICE_TEST}
        ${DOCKER} image tag "${IMAGE}:latest" "${IMAGE}:${TAG_TEST}"
        ${SYSTEMCTL} start ${SERVICE_TEST}
        ;;
    test_prod)
	res=$(compare_images "${TAG_PROD}" "${TAG_TEST}")
        if [[ $res -eq 0 ]]; then
            echo "already up to date"
            exit 1
        fi
        ${DOCKER} exec -t "gitlab_${TAG_PROD}" $BACKUP_CMD
        ${SYSTEMCTL} stop ${SERVICE_PROD}
        ${DOCKER} image tag "${IMAGE}:${TAG_PROD}" "${IMAGE}:${TAG_PREV}"
        ${DOCKER} image tag "${IMAGE}:${TAG_TEST}" "${IMAGE}:${TAG_PROD}"
        ${SYSTEMCTL} start ${SERVICE_PROD}
        ;;
    revert_prod)
	res=$(compare_images "${TAG_PREV}" "${TAG_PROD}")
        if [[ $res -eq 0 ]]; then
            echo "already up to date"
            exit 1
        fi
        ${SYSTEMCTL} stop ${SERVICE_PROD}
        ${DOCKER} image tag "${IMAGE}:${TAG_PREV}" "${IMAGE}:${TAG_PROD}"
        ${SYSTEMCTL} start ${SERVICE_PROD}
        ;;
    *)
        echo "Usage: $0 (check|check_nagios|lastet_test|test_prod|revert_prod)"
        ;;
esac
