#!/usr/bin/env bash
#
# Installs Emakin with Docker Compose on a clean Linux host.
#
#   curl -fsSL https://doc.emakin.com/redir/install | sudo bash
#
# Optional environment variables:
#   AK_DEFAULT_ADMIN     Initial administrator user ID and email (default: admin@emakin.com)
#   AK_DEFAULT_PASSWORD  Initial administrator password (default: generated and printed at the end)
#   EMAKIN_DIR           Installation directory (default: /opt/emakin)
#   EMAKIN_COMPOSE_URL   Compose file to download (default: the file published next to this script)
#
#   curl -fsSL https://doc.emakin.com/redir/install | sudo AK_DEFAULT_ADMIN='admin@example.com' AK_DEFAULT_PASSWORD='change-me' bash
#
# Running the script again keeps the existing Compose and .env files.

set -euo pipefail

EMAKIN_DIR="${EMAKIN_DIR:-/opt/emakin}"
EMAKIN_COMPOSE_URL="${EMAKIN_COMPOSE_URL:-https://wiki.emakin.com/system-administrator-guide/installation/attachments/docker-compose.yml}"
REQUIRED_PORTS=(80 443 7180 25 587 465)
STARTUP_TIMEOUT_SECONDS=900
GENERATED_ADMIN_PASSWORD=""

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

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

# Pixel map of the Emakin logo. Each character is one pixel and two rows form one terminal line.
LOGO_PIXELS=(
    "..........SS............"
    "...........S............"
    "........DDDSDDDDD......."
    "......LLGGDDSDOOOOOO...."
    "....LLLLGGGDDDOOOOOOOO.."
    "...LLLLGGSGDOOOOOOOOOOD."
    "..LLLLGGSGGDOOOOOOOOOOD."
    ".HLLLGGSGGDOOOOOOOOOODD."
    ".DLLGGSSGDOOOOOOOOOOODDH"
    ".DDGGGSSGDOOOOOOOOOOODDH"
    ".DDDGSSGDOOOOODODOOOODDH"
    ".DDDGGGGDOOOOOOYOOOOODDH"
    ".DDDGGGDOOOOOOODOOOOOODH"
    ".DDDGGSDOOOOOOODOOOOOOOH"
    ".HDDGSDOOOOOOOODOOOOOOO."
    "..DODDOOOOOOOOODOOOOOOO."
    "..DOOOOOOOOOOOODOOOOOOH."
    "..OOOOOOOOOOOOODOOOOOO.."
    "..HOOOOOOOOOOOOOOOOOOH.."
    "...HOOOOOOOOOOOOOOOOO..."
    "....OODDDOOOOOOOOOOO...."
    ".....HDDDDDOOOOOOOO....."
    "..........HDDDDDDD......"
    "........................"
)

LOGO_TEXT=(
    ""
    ""
    "                       _    _"
    "  ___ _ __ ___   __ _ | | _(_)_ __"
    " / _ \\ '_ \` _ \\ / _\` || |/ / | '_ \\"
    "|  __/ | | | | | (_| ||   <| | | | |"
    " \\___|_| |_| |_|\\__,_||_|\\_\\_|_| |_|"
    ""
    "  Docker installer"
    ""
    ""
    ""
)

logo_color() {
    case "$1" in
        O) printf '208' ;;
        D) printf '166' ;;
        H) printf '214' ;;
        Y) printf '220' ;;
        L) printf '149' ;;
        G) printf '106' ;;
        S) printf '58' ;;
    esac
}

print_banner() {
    # Plain output when the terminal cannot show colors.
    if [ ! -t 1 ] || [ "${TERM:-dumb}" = "dumb" ]; then
        printf '\nEmakin Docker installer\n\n'
        return
    fi

    local esc=$'\033'
    local index
    local x

    printf '\n'

    for ((index = 0; index < ${#LOGO_PIXELS[@]}; index += 2)); do
        local top="${LOGO_PIXELS[index]}"
        local bottom="${LOGO_PIXELS[index + 1]}"
        local line="  "

        for ((x = 0; x < ${#top}; x++)); do
            local upper="${top:x:1}"
            local lower="${bottom:x:1}"

            if [ "$upper" = "." ] && [ "$lower" = "." ]; then
                line+="${esc}[0m "
            elif [ "$upper" = "." ]; then
                line+="${esc}[0m${esc}[38;5;$(logo_color "$lower")m▄"
            elif [ "$lower" = "." ]; then
                line+="${esc}[0m${esc}[38;5;$(logo_color "$upper")m▀"
            else
                line+="${esc}[38;5;$(logo_color "$upper");48;5;$(logo_color "$lower")m▀"
            fi
        done

        printf '%s%s[0m   %s[1;38;5;208m%s%s[0m\n' "$line" "$esc" "$esc" "${LOGO_TEXT[index / 2]}" "$esc"
    done

    printf '\n'
}

# Runs a quiet command, shows a spinner with the elapsed time, and prints the output only when the command fails.
run_with_progress() {
    local message="$1"
    shift

    local output
    output="$(mktemp)"

    "$@" > "$output" 2>&1 &
    local pid=$!

    if [ -t 1 ]; then
        local frames="|/-\\"
        local elapsed=0

        while kill -0 "$pid" 2>/dev/null; do
            printf '\r\033[1;34m==>\033[0m %s %s %ds ' "$message" "${frames:elapsed % 4:1}" "$elapsed"
            sleep 1
            elapsed=$((elapsed + 1))
        done

        printf '\r\033[K'
    else
        log "$message"
    fi

    if ! wait "$pid"; then
        tail -n 30 "$output" >&2
        fail "$message failed. Full output: $output"
    fi

    rm -f "$output"
    log "$message: done"
}

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

    if [ "$(uname -s)" != "Linux" ]; then
        fail "This script supports Linux hosts only."
    fi

    # All images in the Compose file are published for linux/amd64 and linux/arm64.
    case "$(uname -m)" in
        x86_64 | amd64 | aarch64 | arm64)
            ;;
        *)
            fail "Unsupported architecture $(uname -m). An x86-64 or ARM64 host is required."
            ;;
    esac

    if ! command -v curl >/dev/null 2>&1; then
        fail "curl is required. Install it with your package manager and run the script again."
    fi
}

install_docker() {
    if command -v docker >/dev/null 2>&1 && docker compose version >/dev/null 2>&1; then
        log "Docker is already installed: $(docker --version)"
    else
        local installer
        installer="$(mktemp)"
        curl -fsSL https://get.docker.com -o "$installer"

        run_with_progress "Installing Docker Engine and the Compose plugin" sh "$installer"
        rm -f "$installer"

        log "Installed $(docker --version)"
    fi

    # Failures are reported by the docker info check below.
    if command -v systemctl >/dev/null 2>&1; then
        systemctl enable --now docker >/dev/null 2>&1 || true
    fi

    if ! docker info >/dev/null 2>&1; then
        fail "The Docker daemon is not running."
    fi

    if ! docker compose version >/dev/null 2>&1; then
        fail "The Docker Compose plugin is not available."
    fi
}

generate_password() {
    head -c 24 /dev/urandom | od -An -tx1 | tr -d ' \n'
}

# Short password for the first sign-in. Similar looking characters (0, O, 1, l, I) are left out.
generate_admin_password() {
    local characters
    characters="$(head -c 512 /dev/urandom | LC_ALL=C tr -dc 'A-HJ-NP-Za-km-z2-9')"

    printf '%s' "${characters:0:8}"
}

prepare_compose_file() {
    mkdir -p "$EMAKIN_DIR"
    cd "$EMAKIN_DIR"

    if [ -f docker-compose.yml ]; then
        log "Keeping the existing $EMAKIN_DIR/docker-compose.yml"
        return
    fi

    log "Downloading the Compose file..."
    curl -fsSL "$EMAKIN_COMPOSE_URL" -o docker-compose.yml.tmp

    if ! grep -q "POSTGRES_PASSWORD=ALTIKARE" docker-compose.yml.tmp; then
        rm -f docker-compose.yml.tmp
        fail "The downloaded Compose file does not have the expected database settings."
    fi

    # Replace the sample database password with a generated one.
    local password
    password="$(generate_password)"
    sed -i \
        -e "s/POSTGRES_PASSWORD=ALTIKARE/POSTGRES_PASSWORD=${password}/" \
        -e "s/Password=ALTIKARE;/Password=${password};/g" \
        docker-compose.yml.tmp

    chmod 600 docker-compose.yml.tmp
    mv docker-compose.yml.tmp docker-compose.yml
}

prepare_env_file() {
    if [ -f .env ]; then
        if [ -n "${AK_DEFAULT_ADMIN:-}${AK_DEFAULT_PASSWORD:-}" ]; then
            log "Ignoring AK_DEFAULT_ADMIN and AK_DEFAULT_PASSWORD because $EMAKIN_DIR/.env already exists."
        fi
    else
        local admin="${AK_DEFAULT_ADMIN:-admin@emakin.com}"
        local password="${AK_DEFAULT_PASSWORD:-}"

        if [ -z "$password" ]; then
            password="$(generate_admin_password)"
            GENERATED_ADMIN_PASSWORD="$password"
        fi

        # Values are written single-quoted, so Compose reads them literally.
        case "${admin}${password}" in
            *"'"* | *$'\n'*)
                fail "AK_DEFAULT_ADMIN and AK_DEFAULT_PASSWORD must not contain single quotes or line breaks."
                ;;
        esac

        log "Writing the initial administrator settings to $EMAKIN_DIR/.env"
        (
            umask 077
            printf "AK_DEFAULT_ADMIN='%s'\nAK_DEFAULT_PASSWORD='%s'\n" "$admin" "$password" > .env
        )
    fi

    # The .env file is the only source for Compose from now on.
    unset AK_DEFAULT_ADMIN AK_DEFAULT_PASSWORD
}

check_ports() {
    # Ports held by an already running stack are expected.
    if [ -n "$(docker compose ps -q 2>/dev/null)" ]; then
        return
    fi

    if ! command -v ss >/dev/null 2>&1; then
        log "Skipping the port check because ss is not available."
        return
    fi

    local busy=()
    local port

    for port in "${REQUIRED_PORTS[@]}"; do
        if ss -Htln "sport = :${port}" | grep -q .; then
            busy+=("$port")
        fi
    done

    if [ "${#busy[@]}" -gt 0 ]; then
        fail "These ports are already in use: ${busy[*]}. Stop the services that use them and run the script again."
    fi
}

start_services() {
    log "Pulling images. This can take several minutes..."
    docker compose pull

    log "Starting services..."
    docker compose up -d
}

wait_for_emakin() {
    local message="Waiting for Emakin to respond on port 80"
    local elapsed=0

    if [ ! -t 1 ]; then
        log "$message"
    fi

    while [ "$elapsed" -lt "$STARTUP_TIMEOUT_SECONDS" ]; do
        if [ "$(curl -s -o /dev/null -w '%{http_code}' http://localhost/ || true)" != "000" ]; then
            if [ -t 1 ]; then
                printf '\r\033[K'
            fi

            log "$message: done (${elapsed}s)"
            return
        fi

        if [ -t 1 ]; then
            printf '\r\033[1;34m==>\033[0m %s... %ds ' "$message" "$elapsed"
        fi

        sleep 5
        elapsed=$((elapsed + 5))
    done

    if [ -t 1 ]; then
        printf '\n'
    fi

    fail "Emakin did not respond within ${STARTUP_TIMEOUT_SECONDS} seconds. Check the logs with: cd $EMAKIN_DIR && docker compose logs emakin"
}

print_summary() {
    local host
    host="$(hostname -I 2>/dev/null | awk '{print $1}')"
    host="${host:-localhost}"

    local admin
    admin="$(sed -n "s/^AK_DEFAULT_ADMIN='\(.*\)'$/\1/p" .env)"

    local password="${GENERATED_ADMIN_PASSWORD:-(see ${EMAKIN_DIR}/.env)}"

    cat <<EOF

Emakin is running.

  Application:          http://${host}
  Host Administration:  https://${host}:7180
  Admin user:           ${admin}
  Admin password:       ${password}

  The administrator is created only when no domain exists yet.
  Change the password after the first sign-in.

  Installation folder:  ${EMAKIN_DIR}
  Logs:                 cd ${EMAKIN_DIR} && docker compose logs -f emakin

EOF
}

main() {
    print_banner
    check_host
    install_docker
    prepare_compose_file
    prepare_env_file
    check_ports
    start_services
    wait_for_emakin
    print_summary
}

main "$@"
