#!/bin/bash

# settings
CURDIR=$(dirname $(realpath $0))                    # absolute path to this script
DCBIN="docker compose"                              # path to docker-compose binary

# colors for nice output
RED='\033[0;31m'
GREEN='\033[0;32m'
NOCOLOR='\033[0m'

INSTALL_DIR="${1:-/opt/dmp}"
PORTALDIR="$INSTALL_DIR/portal"

# print command usage and exit
usage() {
    echo -e "\nThis script uninstalls WA/DMP Docker (singlemachine) stack and administrative portal.\n"
    echo -e "Supported OS:  Ubuntu 22/24 LTS, RHEL 9/10"
    echo -e "Version:       1.1.0"
    echo -e "Usage:         $0 INSTALLDIR"
    echo -e "Example:       $0 /opt/dmp\n"
    exit 1
}

# print nicely aligned output
log() {
    printf "%-50s" "$@ "
}

# print green message (OK by default)
log_ok() {
    [[ -z "$1" ]] && MSG="OK" || MSG=$1
    echo -e "[ ${GREEN}$MSG${NOCOLOR} ]"
}

# print error message and exit with code 1
log_fail() {
    echo -e "[ ${RED}FAIL${NOCOLOR} ]"
    [[ -z "$@" ]] || echo -e "\n${RED}Last error:${NOCOLOR}\n$@"
    return 1
}

# print error message and exit with code 1
fail() {
    echo -e "\n$1" >&2
    exit 1
}

# run command, capture stderr and check result
# does not work with pipes and output redirection, great for simple commands
run_command() {
    ERRORS=$("$@" 2>&1 > /dev/null)
    [[ $? == 0 ]] && log_ok || fail "$ERRORS"
}

[[ -n "$1" ]] || echo -e "No installation path provided. Using '$INSTALL_DIR' as default.\n"
[[ ! -d "$INSTALL_DIR" ]] && fail "Install path $INSTALL_DIR does not belong to an existing directory"

log "Checking if Docker is running"
run_command sudo docker info || fail "Docker is not running"

log "Shutting down DMP Stack"
run_command sudo $DCBIN -f "$INSTALL_DIR/dmp/docker-compose.yml" down
 
log "Shutting down the administrative portal"
run_command bash -c "cd '$PORTALDIR' && sudo $DCBIN down"

log "Removing install dir $1"
run_command sudo rm -rf "$INSTALL_DIR"

log "Removing docker volumes"
sudo docker volume rm dmp_cassandra_data dmp_consul_data dmp_content_delivery_data dmp_elasticsearch_data \
                      dmp_graylog_data dmp_mongo_data dmp_postgres_data dmp_hub_runner_data \
                      dmp_broker_internal_data &>/dev/null
log_ok

log "Removing docker network"
run_command sudo docker network rm -f dmp_vpn_hubs

log "Uninstall complete"
echo ""

