#!/usr/bin/env bash
#
# Removes an Emakin installation created by install.sh.
#
#   curl -fsSL https://doc.emakin.com/redir/uninstall | sudo bash
#
# By default, containers and the network are removed. Data volumes, images, and the installation folder are kept,
# so running install.sh again starts with the existing data.
#
# Optional environment variables:
#   EMAKIN_DIR    Installation directory (default: /opt/emakin)
#   EMAKIN_PURGE  Set to 1 to also delete all data volumes, images, and the installation folder. This cannot be undone.
#
#   curl -fsSL https://doc.emakin.com/redir/uninstall | sudo EMAKIN_PURGE=1 bash
#
# Docker Engine itself is not removed.

set -euo pipefail

EMAKIN_DIR="${EMAKIN_DIR:-/opt/emakin}"
EMAKIN_PURGE="${EMAKIN_PURGE:-0}"

log() {
    printf '\033[1;34m==>\033[0m %s\n' "$*"
}

fail() {
    printf '\033[1;31mError:\033[0m %s\n' "$*" >&2
    exit 1
}

check_host() {
    if [ "$(id -u)" -ne 0 ]; then
        fail "Run this script as root, for example: curl -fsSL <url> | sudo bash"
    fi

    if ! command -v docker >/dev/null 2>&1 || ! docker compose version >/dev/null 2>&1; then
        fail "Docker with the Compose plugin is not installed, so there is nothing to remove."
    fi

    if [ ! -f "$EMAKIN_DIR/docker-compose.yml" ]; then
        fail "No Emakin installation was found in $EMAKIN_DIR."
    fi
}

confirm_purge() {
    # The script is usually piped into bash, so the answer is read from the terminal.
    if [ ! -r /dev/tty ]; then
        fail "EMAKIN_PURGE=1 needs a terminal for confirmation."
    fi

    printf '\033[1;31mWarning:\033[0m all Emakin data in %s and its Docker volumes will be deleted permanently.\n' "$EMAKIN_DIR"
    printf 'Type DELETE to continue: '

    local answer
    read -r answer < /dev/tty

    if [ "$answer" != "DELETE" ]; then
        fail "Cancelled. Nothing was removed."
    fi
}

remove_services() {
    cd "$EMAKIN_DIR"

    if [ "$EMAKIN_PURGE" = "1" ]; then
        log "Removing containers, network, data volumes, and images..."
        docker compose --profile "*" down --volumes --rmi all --remove-orphans

        cd /
        rm -rf "$EMAKIN_DIR"
        log "Removed $EMAKIN_DIR"
    else
        log "Removing containers and network..."
        docker compose --profile "*" down --remove-orphans
    fi
}

print_summary() {
    if [ "$EMAKIN_PURGE" = "1" ]; then
        printf '\nEmakin was removed together with all of its data.\n\n'
    else
        cat <<EOF

Emakin was stopped and its containers were removed.

  Kept:  data volumes, images, and ${EMAKIN_DIR}
  Start again:      curl -fsSL https://doc.emakin.com/redir/install | sudo bash
  Delete all data:  curl -fsSL https://doc.emakin.com/redir/uninstall | sudo EMAKIN_PURGE=1 bash

EOF
    fi
}

main() {
    check_host

    if [ "$EMAKIN_PURGE" = "1" ]; then
        confirm_purge
    fi

    remove_services
    print_summary
}

main "$@"
