#!/bin/bash

COMPOSE_PATH="/etc/docker/compose"
COMPOSE_FILE=${COMPOSE_PATH}/"docker-xivocc.yml"
COMPOSE_OVERRIDE_FILE=${COMPOSE_PATH}/"docker-xivocc.override.yml"
CHAT_BACKEND_COMPOSE_FILE=${COMPOSE_PATH}/"docker-xivo-chat-backend.yml"
ENV_FILE=${COMPOSE_PATH}/".env"
FACTORY_ENV_FILE=${COMPOSE_PATH}/"factory.env"
CUSTOM_ENV_FILE=${COMPOSE_PATH}/"custom.env"

HEADER="# This is an auto-generated file, please customize your configuration in the $CUSTOM_ENV_FILE file"

usage() {
    cat <<-EOF
	Usage examples:
	    xivocc-dcomp up -d            start XiVO-CC
	    xivocc-dcomp stop             stop XiVO-CC
	    xivocc-dcomp pull             pull docker images
	    xivocc-dcomp version          list running containers and their version
	    xivocc-dcomp version -a       list all containers and their version
	    xivocc-dcomp version -i       list images and their version
	    xivocc-dcomp config           display config that will be used
	    xivocc-dcomp reload SERVICE   reload SERVICE configuration
	                                    SERVICE can be one of: nginx, pgxivocc
	Run 'docker compose --help' for full command list
    For further help see XiVO-CC installation page at https://documentation.xivo.solutions
	EOF
    exit "$1"
}

check_args() {
    if [ -z "$1" ]; then
        usage 0
    fi
}

check_file() {
    local filepath="${1}"
    shift
    local exitcode="${1}"
    shift

    if [ ! -f "${filepath}" ]; then
        echo "Required file (${filepath}) does not exist, exiting"
        exit "${exitcode}"
    fi
}

check_files() {
    check_file $COMPOSE_FILE "1"
    check_file $FACTORY_ENV_FILE "2"
    check_file $CUSTOM_ENV_FILE "3"
}

rewrite_env_file() {
    echo "$HEADER" >$ENV_FILE
    cat $FACTORY_ENV_FILE $CUSTOM_ENV_FILE >>$ENV_FILE
    if [ $? -ne 0 ]; then
        echo "Error writing $ENV_FILE file"
        exit 4
    fi
}

is_xivouc() {
    [ -f /var/lib/xivo/uc_enabled ]
}

run_compose() {
    cd $COMPOSE_PATH || usage 1

    compose_files="-f $COMPOSE_FILE"
    if [ -f $COMPOSE_OVERRIDE_FILE ]; then
        compose_files+=" -f $COMPOSE_OVERRIDE_FILE"
    fi
    if [ -f $CHAT_BACKEND_COMPOSE_FILE ]; then
        compose_files+=" -f $CHAT_BACKEND_COMPOSE_FILE"
    fi
    for file in $(ls -w 0 -x ${COMPOSE_PATH}/[0-9][0-9]-*.override.yml 2>/dev/null); do
        compose_files+=" -f $file"
    done

    #shellcheck disable=SC2086,SC2068
    docker compose -p xivocc $compose_files $@
}

display_running_version() {
    docker ps --format 'table {{.Names}}\t{{.Label "version"}}'
}

display_all_version() {
    docker ps -a --format 'table {{.Names}}\t{{.Label "version"}}'
}

display_images_version() {
    docker inspect --format '{{.RepoTags}}: {{.Config.Labels.version}}' $(docker images xivoxc/* --format '{{.ID}}' | grep -v '<none>' | uniq) | grep -v '\[\]'
}

check_args "$@"
check_files

if [ "$1" != "ps" ]; then
    rewrite_env_file
fi

if [ "$1" = "version" ]; then
    if [ -z "$2" ]; then
        display_running_version
    elif [ "$2" = "-a" ]; then
        display_all_version
    elif [ "$2" = "-i" ]; then
        display_images_version
    else
        echo "Unknown modifier '$2'"
        exit 5
    fi
elif [ "$1" = "upgrade-db" ]; then
    run_compose pull pgxivocc
    run_compose up -d pgxivocc
elif [ "$1" = "reload" ]; then
    if [ "$2" = "nginx" ] || [ "$2" = "pgxivocc" ]; then
        run_compose kill -s SIGHUP "$2"
    else
        echo "Reload for $2 is not supported"
    fi
else
    run_compose "$@"
fi
