#!/bin/sh

set -e

#
# CONFIG
#

# Try to load additional environment variables
# The default path is /etc/default/helfertool and can be overwritten with
# HELFERTOOLCTL_ENV.
# Alternatively, the other environment variables can also be set directly.
test "$HELFERTOOLCTL_ENV" || HELFERTOOLCTL_ENV="/etc/default/helfertool"

if [ -n "$HELFERTOOLCTL_ENV" ] ; then
    if [ -f "$HELFERTOOLCTL_ENV" ] ; then
        . "$HELFERTOOLCTL_ENV"
    else
        echo "Warning: cannot read configuration file \"$HELFERTOOLCTL_ENV\""
    fi
fi

# Now the default configuration is set, unless the variable is already set.
# The variables can be set directly as environment variables or in the
# file specified as HELFERTOOLCTL_ENV

# The user and group that will be used to run the container
test "$HELFERTOOL_USER" || HELFERTOOL_USER="helfertool"
test "$HELFERTOOL_GROUP" || HELFERTOOL_GROUP="helfertool"

# Name of the docker image from the docker hub
test "$HELFERTOOL_DOCKER_IMAGE" || HELFERTOOL_DOCKER_IMAGE="helfertool/helfertool"

# Name of the docker container that is started
test "$HELFERTOOL_DOCKER_NAME" || HELFERTOOL_DOCKER_NAME="helfertool"

# Path of config, data and log files
test "$HELFERTOOL_CONFIG_DIR" || HELFERTOOL_CONFIG_DIR="/etc/helfertool"
test "$HELFERTOOL_DATA_DIR" || HELFERTOOL_DATA_DIR="/srv/helfertool"
test "$HELFERTOOL_LOG_DIR" || HELFERTOOL_LOG_DIR="/var/log/helfertool"

# Listen address and port
test "$HELFERTOOL_ADDRESS" || HELFERTOOL_ADDRESS="127.0.0.1"
test "$HELFERTOOL_PORT" || HELFERTOOL_PORT="8000"

#
# FUNCTIONS
#

docker_is_running()
{
    if [ -z "$(docker ps -a --format "{{.Names}}" | grep "^$HELFERTOOL_DOCKER_NAME$")" ] ; then
        return 1  # false, not running
    else
        return 0  # true, running
    fi
}

docker_exec()
{
    /usr/bin/docker exec -t "$HELFERTOOL_DOCKER_NAME" $@
}

docker_exec_interactive()
{
    /usr/bin/docker exec -it "$HELFERTOOL_DOCKER_NAME" $@
}

#
# MAIN
#

# Command: start
if [ "$1" = "start" ] ; then
    # check if container is currently running and stop it
    if docker_is_running ; then
        /usr/bin/docker stop "$HELFERTOOL_DOCKER_NAME" || true
        /usr/bin/docker rm "$HELFERTOOL_DOCKER_NAME" || true
    fi

    /usr/bin/docker run --rm --name "$HELFERTOOL_DOCKER_NAME" \
        -p "$HELFERTOOL_ADDRESS:$HELFERTOOL_PORT:8000" \
        --user $(id -u "$HELFERTOOL_USER") \
        --group-add $(id -g "$HELFERTOOL_GROUP") \
        --read-only \
        -v "$HELFERTOOL_DATA_DIR:/data" \
        -v "$HELFERTOOL_CONFIG_DIR:/config" \
        -v "$HELFERTOOL_LOG_DIR:/log" \
        --tmpfs "/helfertool/run" \
        "$HELFERTOOL_DOCKER_IMAGE"

# Command: stop
elif [ "$1" = "stop" ] ; then
    /usr/bin/docker stop "$HELFERTOOL_DOCKER_NAME"

# Command: reload
elif [ "$1" = "reload" ] ; then
    docker_exec helfertool reload

# Command: download
elif [ "$1" = "download" ] ; then
    echo "Cleanup..."
    docker_image="$(echo "$HELFERTOOL_DOCKER_IMAGE" | sed 's/:[^:]*$//g')"
    old_images="$(docker images --filter "dangling=true" "$docker_image" --quiet)"
    if [ "$old_images" != "" ] ; then
        /usr/bin/docker image rm $old_images > /dev/null || true  # ignore errors
    fi

    echo "Getting new image..."
    /usr/bin/docker pull "$HELFERTOOL_DOCKER_IMAGE" | grep --color=never "^Status:"

# Command: needsrestart
elif [ "$1" = "needsrestart" ] ; then
    if docker_is_running ; then
        # currently used image id
        image_running="$(/usr/bin/docker inspect --format="{{.Image}}" "$HELFERTOOL_DOCKER_NAME")"

        # get latest image id
        # needs to look for helfertool/helfetool:latest instead of helfertool/helfertool, otherwise
        # all other tags are also listed
        if [ -z "$(echo "$HELFERTOOL_DOCKER_IMAGE" | grep ":")" ] ; then
            image="$HELFERTOOL_DOCKER_IMAGE:latest"
        else
            image="$HELFERTOOL_DOCKER_IMAGE"
        fi

        image_current="$(docker images --no-trunc --format="{{.ID}}" "$image")"

        # check
        if [ "$image_running" != "$image_current" ] ; then
            echo "Restart needed"
        fi
    fi

# Command: postrotate
elif [ "$1" = "postrotate" ] ; then
    docker_exec helfertool postrotate

# Command: init
elif [ "$1" = "init" ] ; then
    docker_exec helfertool init

# Command: createadmin
elif [ "$1" = "createadmin" ] ; then
    docker_exec_interactive helfertool manage createsuperuser

# Command: open
elif [ "$1" = "open" ] ; then
    shift
    docker_exec helfertool manage openregistration $@

# Command: close
elif [ "$1" = "close" ] ; then
    shift
    docker_exec helfertool manage closeregistration $@

# Command: disableaccounts
elif [ "$1" = "disableaccounts" ] ; then
    shift
    docker_exec helfertool manage disableaccounts $@

# Command: exampledata
elif [ "$1" = "exampledata" ] ; then
    shift
    docker_exec helfertool manage exampledata $@

# Command: statistics
elif [ "$1" = "statistics" ] ; then
    docker_exec helfertool manage helfertoolstats

# Command: manage
elif [ "$1" = "manage" ] ; then
    shift
    docker_exec_interactive helfertool manage $@

# Command: shell
elif [ "$1" = "shell" ] ; then
    shift
    docker_exec_interactive bash

# Help
else
    echo "helfertoolctl"
    echo ""
    echo "[Service]"
    echo "start\t\tStart docker container"
    echo "stop\t\tStop docker container"
    echo "reload\t\tReload application"
    echo "download\tDownload the latest Docker image"
    echo ""
    echo "needsrestart\tCheck if a newer container is available locally (after download)"
    echo "postrotate\tCall after logs were rotated"
    echo ""
    echo "[Helfertool]"
    echo "init\t\tInitialize Helfertool (only run once at the beginning!)"
    echo "createadmin\tCreate new adminitrator account"
    echo "open\t\tOpen registration for event (parameter: URL name)"
    echo "close\t\tClose registration for event (parameter: URL name)"
    echo "disableaccounts\tDisabled accounts which are inactive since the specified time (parameters: date (YYYY-MM-DD) and optionally --dry-run)"
    echo "exampledata\tAdd an example event (no inventory settings are changed as these are global)"
    echo "statistics\tPrint some numbers"
    echo ""
    echo "[Advanced]"
    echo "manage\t\tRun Django manage.py command directly"
    echo "shell\t\tSpawn shell in docker container"

    exit 1
fi
