#!/bin/sh
#
# Installs self-hosted Redbrix with Docker: on a Linux server, macOS, or Windows in Git Bash or WSL.
#
#   curl -fsSL https://app.redbrix.io/self-hosted/install.sh | sh
#
# You are welcome to read this before running it; it is short. It:
#   1. checks Docker and Docker Compose are installed;
#   2. asks whether to serve Redbrix over HTTPS, and the address people will use;
#   3. makes a folder (./redbrix) holding docker-compose.yml and a .env file with new keys and a
#      new database password, generated here on this server (and, for HTTPS, a Caddyfile);
#   4. starts Redbrix and prints the setup code to enter in your browser.
#
# HTTPS is served by Caddy (https://caddyserver.com), a separate container, in one of two ways:
#   auto - a certificate from Let's Encrypt, fetched and renewed automatically. The server needs
#          a public name, and ports 80 and 443 reachable from the internet.
#   own  - your own certificate and key files, such as one from your organisation's own
#          certificate authority. For servers on an internal network.
#
# It changes nothing outside that folder, needs no root (beyond whatever your Docker needs), and
# sends nothing anywhere. To answer the questions in advance, set REDBRIX_HTTPS (none, auto or
# own), REDBRIX_URL (or REDBRIX_NAME with HTTPS), REDBRIX_PORT, REDBRIX_HTTPS_PORT,
# REDBRIX_HTTP_PORT, REDBRIX_CERT, REDBRIX_KEY and REDBRIX_DIR. REDBRIX_IMAGE chooses a release, such as ghcr.io/redbrix-io/redbrix:1.4.

set -eu

SOURCE="${REDBRIX_SOURCE:-https://app.redbrix.io/self-hosted}"
IMAGE="${REDBRIX_IMAGE:-ghcr.io/redbrix-io/redbrix:latest}"
DIR="${REDBRIX_DIR:-redbrix}"

say() { printf '%s\n' "$*"; }
stop() { printf 'Stopped: %s\n' "$*" >&2; exit 1; }

# Questions are read from the terminal, because when this script is piped in from curl, its own
# input is the script.
ask() {
    printf '%s [%s]: ' "$1" "$2" >/dev/tty
    read -r answer </dev/tty || answer=""
    printf '%s' "${answer:-$2}"
}

# Which host name reaches a database on this computer. Inside the container, localhost is the
# container. With Docker installed inside a WSL Linux distribution (not Docker Desktop),
# host.docker.internal is that Linux system, and a database on Windows is at Windows's address.
local_database_hint() {
    if grep -qi microsoft /proc/version 2>/dev/null && ! docker info 2>/dev/null | grep -q 'Docker Desktop'; then
        mode=$(wslinfo --networking-mode 2>/dev/null) || mode=nat
        windows=$(ip route show default 2>/dev/null | awk '{print $3; exit}')
        if [ "$mode" = "nat" ] && [ -n "$windows" ]; then
            say "Connecting to a database on Windows: use the host name $windows (Windows, as seen"
            say "from this Linux system; it can change when Windows restarts), not localhost."
        else
            say "Connecting to a database on Windows: use Windows's network address, not localhost."
        fi
        say "For a database inside this Linux system, use host.docker.internal."
    else
        say "Connecting to a database on this computer: use the host name host.docker.internal,"
        say "not localhost (inside Redbrix's container, localhost is the container itself)."
    fi
}

random_password() {
    if command -v openssl >/dev/null 2>&1; then
        openssl rand -base64 24 | tr -d '/+=\n'
    else
        head -c 24 /dev/urandom | base64 | tr -d '/+=\n'
    fi
}

# ── 1. Docker ─────────────────────────────────────────────────────────────────────────────────
command -v docker >/dev/null 2>&1 || stop "Docker is not installed. See https://docs.docker.com/engine/install/"
docker compose version >/dev/null 2>&1 || stop "Docker Compose is not installed. See https://docs.docker.com/compose/install/"
docker info >/dev/null 2>&1 || stop "Docker is installed but not running, or this user cannot use it."

[ ! -e "$DIR/.env" ] || stop "$DIR/.env already exists. Redbrix seems to be installed there already; nothing was changed."

# Docker names the database volume after the folder, and keeps it when the folder is deleted. A
# new install would find the old database, with the old password, and be refused.
project=$(basename "$DIR" | tr 'A-Z' 'a-z' | tr -cd 'a-z0-9_-')
if docker volume inspect "${project}_redbrix-data" >/dev/null 2>&1; then
    stop "the database of an earlier Redbrix install, the Docker volume ${project}_redbrix-data, is still here.
If you no longer need it, remove it with: docker volume rm ${project}_redbrix-data
Or install into another folder by setting REDBRIX_DIR. Nothing was changed."
fi

# ── 2. Questions ──────────────────────────────────────────────────────────────────────────────
say "Installing self-hosted Redbrix into ./$DIR"
https="${REDBRIX_HTTPS:-$(ask "HTTPS: none (plain HTTP; right for trying it on this computer), auto (a public name, free certificate) or own (your certificate files)" "none")}"

case "$https" in
    none)
        port="${REDBRIX_PORT:-$(ask "Port for Redbrix on this server" "8080")}"
        url="${REDBRIX_URL:-$(ask "Address people will type to reach it" "http://$(hostname -f 2>/dev/null || hostname):$port")}"
        case "$url" in
            http://* | https://*) ;;
            *) stop "the address must start with http:// or https://, such as http://redbrix.example.com:$port" ;;
        esac
        ;;
    auto | own)
        # Redbrix itself listens on this port for this server only; Caddy answers everyone else.
        port="${REDBRIX_PORT:-8080}"
        name="${REDBRIX_NAME:-$(ask "Server name people will type, without https://" "$(hostname -f 2>/dev/null || hostname)")}"
        case "$name" in
            */* | *:* | "") stop "give the name alone, such as redbrix.example.com" ;;
        esac

        if [ "$https" = "own" ]; then
            https_port="${REDBRIX_HTTPS_PORT:-$(ask "HTTPS port" "443")}"
            http_port="${REDBRIX_HTTP_PORT:-$(ask "Plain HTTP port, redirected to HTTPS" "80")}"
            cert="${REDBRIX_CERT:-$(ask "Certificate file (PEM, with any intermediate certificates)" "")}"
            key="${REDBRIX_KEY:-$(ask "Its private key file (PEM)" "")}"
            [ -r "$cert" ] || stop "cannot read the certificate file '$cert'."
            [ -r "$key" ] || stop "cannot read the key file '$key'."
        else
            # Let's Encrypt must reach the server by a public name, on ports 80 and 443. For any
            # other name Caddy would make its own certificate, which browsers warn about.
            if ! printf '%s' "$name" | grep -q '\.' || printf '%s' "$name" | grep -Eq '(^[0-9.]+$|^localhost$|\.(localhost|local|internal|home\.arpa|lan)$)'; then
                stop "$name is not a public name, so Let's Encrypt cannot give it a certificate.
To try Redbrix on this computer, run the installer again and choose \"none\": browsers treat localhost as secure, and nothing leaves the machine.
On a server, use a public name that points to it, such as redbrix.example.com, or choose \"own\" with your own certificate."
            fi
            https_port=443
            http_port=80
            email="${REDBRIX_EMAIL-$(ask "Email for certificate expiry warnings (optional)" "")}"
        fi

        url="https://$name"
        [ "$https_port" = "443" ] || url="$url:$https_port"
        ;;
    *) stop "answer none, auto or own." ;;
esac

# ── 3. Files ──────────────────────────────────────────────────────────────────────────────────
mkdir -p "$DIR"
say "Downloading docker-compose.yml and the instructions..."
curl -fsSL "$SOURCE/docker-compose.yml" -o "$DIR/docker-compose.yml" || stop "could not download $SOURCE/docker-compose.yml"
curl -fsSL "$SOURCE/README.md" -o "$DIR/README.md" || stop "could not download $SOURCE/README.md"

say "Generating keys (this downloads the Redbrix image the first time)..."
app_key=$(docker run --rm "$IMAGE" php artisan key:generate --show) || stop "could not run the Redbrix image to generate keys."
credential_key=$(docker run --rm "$IMAGE" php artisan key:generate --show)

# Readable by this user only: it holds the keys.
umask 077
cat >"$DIR/.env" <<EOF
# Self-hosted Redbrix, written by the installer on $(date '+%Y-%m-%d').
# Keep a copy of this file somewhere safe: without CREDENTIAL_KEY, saved database passwords
# cannot be read. Every setting is explained in README.md.

APP_URL=$url
APP_KEY=$app_key
CREDENTIAL_KEY=$credential_key
DB_PASSWORD=$(random_password)
REDBRIX_PORT=$port
EOF

# A release chosen when installing stays chosen.
[ -z "${REDBRIX_IMAGE:-}" ] || printf 'REDBRIX_IMAGE=%s\n' "$REDBRIX_IMAGE" >>"$DIR/.env"

if [ "$https" != "none" ]; then
    # Caddy in front; Redbrix's own port for this server only; Caddy's forwarded headers believed.
    cat >>"$DIR/.env" <<EOF

# HTTPS through Caddy (the caddy service in docker-compose.yml and the Caddyfile).
COMPOSE_PROFILES=https
REDBRIX_BIND=127.0.0.1
TRUSTED_PROXIES=*
SESSION_SECURE_COOKIE=true
EOF
    [ "$http_port" = "80" ] || printf 'REDBRIX_HTTP_PORT=%s\n' "$http_port" >>"$DIR/.env"
    [ "$https_port" = "443" ] || printf 'REDBRIX_HTTPS_PORT=%s\n' "$https_port" >>"$DIR/.env"

    mkdir -p "$DIR/certs"
    if [ "$https" = "own" ]; then
        cp "$cert" "$DIR/certs/redbrix.crt"
        cp "$key" "$DIR/certs/redbrix.key"
        # The key readable by this user only (Caddy's container reads it as root); the
        # certificate is public anyway.
        chmod 600 "$DIR/certs/redbrix.key"
        chmod 644 "$DIR/certs/redbrix.crt"
        tls="tls /certs/redbrix.crt /certs/redbrix.key"
    else
        tls=""
    fi

    {
        [ -z "${email:-}" ] || printf '{\n\temail %s\n}\n\n' "$email"
        printf '# Redbrix behind HTTPS. Plain HTTP is redirected here.\n'
        # Another HTTPS port is part of the site's address, so Caddy listens on it inside its
        # container (as outside it) and puts it in its redirects from plain HTTP.
        if [ "$https_port" = "443" ]; then printf '%s {\n' "$name"; else printf '%s:%s {\n' "$name" "$https_port"; fi
        [ -z "$tls" ] || printf '\t%s\n' "$tls"
        printf '\treverse_proxy redbrix:8080\n}\n'
    } >"$DIR/Caddyfile"
    chmod 644 "$DIR/Caddyfile"
fi

# ── 4. Start ──────────────────────────────────────────────────────────────────────────────────
# Fetched first: "up" alone uses any copy of the image already on this machine, which may be an
# older release left by an earlier install. A failed fetch is not fatal: an image built on this
# machine (as the install test uses) cannot be fetched, and "up" reports a missing image itself.
say "Downloading Redbrix..."
(cd "$DIR" && docker compose pull --quiet --ignore-pull-failures) || true

say "Starting Redbrix..."
(cd "$DIR" && docker compose up -d) || stop "docker compose could not start Redbrix. Its files are in ./$DIR."

say "Waiting for it to start..."

# Stops with the end of Redbrix's log if it has said it cannot start: waiting longer will not help.
check_started() {
    log=$(cd "$DIR" && docker compose logs --no-log-prefix redbrix 2>/dev/null) || return 0
    if printf '%s\n' "$log" | grep -q 'Redbrix cannot start'; then
        printf '%s\n' "$log" | tail -15 >&2
        stop "Redbrix could not start; the end of its log is above. Its files are in ./$DIR."
    fi
}

code=""
attempt=0
while [ -z "$code" ] && [ "$attempt" -lt 60 ]; do
    sleep 3
    attempt=$((attempt + 1))
    check_started
    code=$(cd "$DIR" && docker compose logs redbrix 2>/dev/null | grep -o 'Setup code: [A-Z0-9-]*' | tail -1 | cut -d' ' -f3) || true
done

# The code is logged a moment before the web server answers, so wait for that too, asking as the
# address's host name: Redbrix answers to no other.
host=$(printf '%s' "$url" | sed -E 's#^https?://([^/:]+).*#\1#')
attempt=0
until curl -fsS -o /dev/null -H "Host: $host" "http://127.0.0.1:$port/up" 2>/dev/null || [ "$attempt" -ge 40 ]; do
    sleep 3
    attempt=$((attempt + 1))
    check_started
done

say ""
if [ -n "$code" ]; then
    say "Redbrix is running."
    say ""
    say "  Open:        $url"
    say "  Setup code:  $code"
    say ""
    say "You will also need your licence key, from your Customer Portal at redbrix.io."
    [ "$https" != "auto" ] || say "The first visit may take a few seconds while the certificate is fetched."
else
    say "Redbrix is starting, but has not shown its setup code yet. In a minute, run:"
    say "  cd $DIR && docker compose logs redbrix"
fi
say ""
local_database_hint
say ""
say "Back up $DIR/.env now: it holds the keys. README.md in $DIR explains upgrading and backups."
