#!/bin/bash

COMPOSE_PATH="/etc/docker/xivo"
COMPOSE_FILE=${COMPOSE_PATH}/"docker-xivo.yml"
COMPOSE_XC_OVERRIDE_FILE=${COMPOSE_PATH}/"docker-xivo.override.yml"
COMPOSE_UC_OVERRIDE_FILE=${COMPOSE_PATH}/"docker-xivo-uc.override.yml"
COMPOSE_IVR_OVERRIDE_FILE=${COMPOSE_PATH}/"docker-xivo-ivr.override.yml"
ENV_FILE=${COMPOSE_PATH}/".env"
FACTORY_ENV_FILE=${COMPOSE_PATH}/"factory.env"
CUSTOM_ENV_FILE=${COMPOSE_PATH}/"custom.env"
XIVOXC_ENABLED_FILE="/var/lib/xivo/xc_enabled"

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

docker_services_enabled="rabbitmq db nginx webi proxy confgend"

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 XiVO docker services
		    xivo-dcomp stop             stop XiVO 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-db        reload postgres configuration
		    xivo-dcomp reload SERVICE   reload SERVICE configuration
		                                  SERVICE can be one of: db, nginx, proxy

		Run 'docker compose --help' for full command list
		For further help see XiVO-CC 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"
}

add_auth_token_to_custom_env_file() {
    local current_static_token
    local actual_static_token

    current_static_token=$(grep -oP -m 1 '^\s*XIVO_CONFD_AUTH_TOKEN=\K.*' ${CUSTOM_ENV_FILE})

    if actual_static_token=$(xivo-auth-static-token-manager get); then
        if [ "$current_static_token" = "" ]; then
            echo "Adding static token to custom.env file"
            echo "XIVO_CONFD_AUTH_TOKEN=${actual_static_token}" >> ${CUSTOM_ENV_FILE}
        else
            if [ "$current_static_token" != "$actual_static_token" ]; then
                echo "Static token changed, updating custom.env file"
                sed -i "s/^XIVO_CONFD_AUTH_TOKEN=.*$/XIVO_CONFD_AUTH_TOKEN=$actual_static_token/g" ${CUSTOM_ENV_FILE}
            fi
        fi
    fi
}

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"
    if [ -f $COMPOSE_UC_OVERRIDE_FILE ]; then
      compose_files+=" -f $COMPOSE_UC_OVERRIDE_FILE"
    fi
    if [ -f $COMPOSE_IVR_OVERRIDE_FILE ]; then
      compose_files+=" -f $COMPOSE_IVR_OVERRIDE_FILE"
    fi
    if [ -f $XIVOXC_ENABLED_FILE ]; then
      compose_files+=" -f $COMPOSE_XC_OVERRIDE_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 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 '\[\]'
}

is_enabled_docker_service() {
    local re="\<$1\>"
    if [[ $docker_services_enabled =~ $re ]]; then
        return 0
    else
        return 1
    fi
}

is_auth_installed() {
    [ "$(which xivo-auth-static-token-manager)" ]
}

check_args $@
check_files
# Define XIVO_UUID in the environment before starting containers
[ -e /etc/profile.d/xivo_uuid.sh ] && source /etc/profile.d/xivo_uuid.sh
if is_auth_installed; then
    add_auth_token_to_custom_env_file
fi

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