#!/bin/bash

COMPOSE_PATH="/etc/docker/mds"
COMPOSE_FILE=${COMPOSE_PATH}/"docker-xivomds.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"

XIVO_DEFAULT_FILE="/etc/default/xivo"
xivo_disabled_file="/var/lib/xivo/disabled"
is_systemd=0

if [ -d /run/systemd/system ]; then
    is_systemd=1
fi


check_args() {
    if [ -z "$1" ]; then
        cat <<-EOF
		Usage examples:
		    xivo-dcomp up -d            start MDS docker services
		    xivo-dcomp stop             stop MDS docker services
		    xivo-dcomp pull             pull docker images
		    xivo-dcomp version          list running containers and their version
		    xivo-dcomp version -a       list all containers and their version
		    xivo-dcomp version -i       list images and their version
		    xivo-dcomp config           display config that will be used
		    xivo-dcomp reload SERVICE   reload SERVICE configuration
		                                  SERVICE can be one of: db

		Run 'docker compose --help' for full command list
		For further help see XiVO-MDS installation page at https://documentation.xivo.solutions
		EOF
        exit 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_xivo_enabled() {
    if [ $is_systemd -eq 0 ]; then
        grep -q 'startup=yes' $XIVO_DEFAULT_FILE
    else
        test ! -f $xivo_disabled_file
    fi
    echo $?
}

run_compose() {
    cd $COMPOSE_PATH
    compose_files="-f $COMPOSE_FILE"
    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 xivo $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 db
    run_compose up -d db
elif [ "$1" = "start-db" ]; then
    run_compose up -d db
elif [ "$1" = "reload-db" ]; then
    # kept for backward compatibility
    run_compose kill -s SIGHUP db
elif [ "$1" = "reload" ]; then
    if [ "$2" = "db" ] ; then
        run_compose kill -s SIGHUP "$2"
    else
        echo "Reload for $2 is not supported"
    fi
elif [ $(is_xivo_enabled) -eq 0 ] || ([ "$1" != "up" ] && [ "$1" != "start" ]) ; then
    run_compose $@
else
    echo "xivo-service is disabled"
fi
