#!/usr/bin/env bash
# ghost-docker: start the ghost-docker manager.
#
#   ghost-docker [--dir PATH] <command> [options]
#   ghost-docker help
#
# Everything ghost-docker does happens in a container, the manager image. This
# script is the only part that runs on the host, and it does three things:
# check that Docker can be used, decide which image to run, and run it with the
# site directory, the Docker socket and your identity. The manager's exit
# status is this script's exit status.
#
#   --dir PATH            The site directory. Default: the current directory.
#   --channel CHANNEL     Run the newest release on a channel: stable or beta.
#   --release, --to TAG   Run this release: vX.Y.Z or vX.Y.Z-beta.N.
#
# --channel, --release and --to choose the image, and are passed on to the command
# too: `install --channel beta`, `install --release v1.2.0`, `self-update --to v1.2.0`.
#
# Which image runs, first match wins:
#
#   GD_IMAGE                 an image you name
#   --release or --to        that release
#   --channel                the newest release on that channel, pulled every time
#   self-update, in a site   the newest release on the channel the site follows
#   a pinned image           written into a site's own copy of this script at install
#   a checkout               this script next to manager/Dockerfile builds from it
#   GD_CHANNEL               a published channel (default: beta), pulled every time
#
# Requires bash and Docker with the Compose plugin. Nothing else. On Windows,
# run it inside WSL2. The contract this implements is
# docs/architecture.md#launcher-and-manager.
set -euo pipefail

readonly GD_REGISTRY_IMAGE="ghcr.io/tryghost/ghost-docker"
# Replaced with `repository@sha256:...` in the copy installed into a site.
readonly GD_PINNED_IMAGE=""
# Replaced with the channel the site follows (stable, beta or edge), which
# `self-update` resolves when no other release is named.
readonly GD_PINNED_CHANNEL=""
# How long Docker may take to answer before it is treated as not running. A
# daemon that has wedged stops answering rather than returning an error.
GD_DOCKER_TIMEOUT=${GD_DOCKER_TIMEOUT:-20}

die() {
    printf 'error: %s\n' "$1" >&2
    exit "${2:-1}"
}

# with_deadline SECONDS COMMAND...
# 124 when the command had to be killed. `timeout(1)` is not on macOS.
with_deadline() {
    local seconds=$1 pid waited=0
    shift
    "$@" &
    pid=$!
    while kill -0 "$pid" 2>/dev/null; do
        if ((waited >= seconds)); then
            kill -9 "$pid" 2>/dev/null
            wait "$pid" 2>/dev/null
            return 124
        fi
        sleep 1
        waited=$((waited + 1))
    done
    wait "$pid"
}

# --- Options that belong to the launcher ------------------------------------

site_dir=""
# The index in args of a path to mount: --import's bundle, or restore's backup.
bundle_at=""
# The first word that is not an option: the command.
command_word=""
channel=""
release=""
declare -a args=()
while (($#)); do
    case $1 in
        --dir)
            [[ ${2:-} ]] || die "--dir needs a path" 2
            site_dir=$2
            shift
            ;;
        --dir=*) site_dir=${1#*=} ;;
        # The manager's options too, and passed on to it; the image is chosen
        # from them here.
        --channel | --release | --to)
            [[ ${2:-} ]] || die "$1 needs a value" 2
            args+=("$1" "$2")
            if [[ $1 == --channel ]]; then channel=$2; else release=$2; fi
            shift
            ;;
        --channel=*)
            args+=("$1")
            channel=${1#*=}
            ;;
        --release=* | --to=*)
            args+=("$1")
            release=${1#*=}
            ;;
        # The manager's option, but the bundle has to be mounted for it to
        # see it; the manager validates it like any other argument.
        --import)
            args+=("$1")
            if (($# > 1)); then
                bundle_at=${#args[@]}
                args+=("$2")
                shift
            fi
            ;;
        --import=*)
            args+=(--import)
            bundle_at=${#args[@]}
            args+=("${1#*=}")
            ;;
        # The end of options: everything after it is the command's own,
        # passed on as it is, never read as a launcher option however it is
        # spelled. restore's backup can still be the first of it.
        --)
            if [[ $command_word == restore && -z $bundle_at && $# -gt 1 ]]; then
                bundle_at=$((${#args[@]} + 1))
            fi
            args+=("$@")
            break
            ;;
        *)
            # restore's backup: the argument after the command, mounted
            # like a bundle when it is outside the site.
            if [[ $command_word == restore && -z $bundle_at && $1 != -* ]]; then
                bundle_at=${#args[@]}
            elif [[ -z $command_word && $1 != -* ]]; then
                command_word=$1
            fi
            args+=("$1")
            ;;
    esac
    shift
done

# Only the release formats that are published; the manager checks them again.
case $channel in
    '' | stable | beta) ;;
    *) die "--channel must be stable or beta: got '$channel'" 2 ;;
esac
if [[ -n $release ]] && ! [[ $release =~ ^v(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)(-beta\.(0|[1-9][0-9]*))?$ ]]; then
    die "a release is vX.Y.Z or vX.Y.Z-beta.N: got '$release'" 2
fi
[[ -z $channel || -z $release ]] || die "choose a channel or a release, not both" 2

# --- Can Docker be used? ----------------------------------------------------
#
# These are the only checks that cannot run in the manager, because without
# them there is no manager. Each says what to do next.

host_os=$(uname -s 2>/dev/null || printf 'unknown')
case $host_os in
    MINGW* | MSYS* | CYGWIN*)
        die "this shell ($host_os) cannot run ghost-docker.
  On Windows, run it inside WSL2: install Docker Desktop with the WSL2 backend,
  open a WSL terminal, and run ./ghost-docker there."
        ;;
esac

command -v docker >/dev/null 2>&1 ||
    die "Docker is not installed, or is not on the PATH.
  Install Docker Engine (Linux) or Docker Desktop: https://docs.docker.com/get-docker/"

# Access is established by asking the daemon, never from group membership:
# neither rootless Docker nor a remote DOCKER_HOST involves the docker group.
rc=0
security=$(with_deadline "$GD_DOCKER_TIMEOUT" docker info --format '{{.SecurityOptions}}' 2>/dev/null </dev/null) || rc=$?
if ((rc == 124)); then
    die "the Docker daemon did not answer within ${GD_DOCKER_TIMEOUT} seconds.
  It may be starting, or stuck. Wait for it to report running, or restart it."
elif ((rc != 0)); then
    die "the Docker daemon is not reachable.
  Start Docker and try again. If it is running, this user may not be allowed to use it:
  check \`docker info\`."
fi

with_deadline "$GD_DOCKER_TIMEOUT" docker compose version >/dev/null 2>&1 </dev/null ||
    die "the Docker Compose plugin is not installed.
  ghost-docker sites are run with \`docker compose\`. See https://docs.docker.com/compose/install/"

rootless=0
case $security in *rootless*) rootless=1 ;; esac

# --- The site directory -----------------------------------------------------

[[ -n $site_dir ]] || site_dir=$PWD
[[ -d $site_dir ]] || die "$site_dir is not a directory. Create it, or name another with --dir." 2
# The daemon resolves Compose bind mounts against host paths, so the manager
# must see the site at exactly the path the host does: resolved, and mounted
# at itself.
site_dir=$(CDPATH='' cd -- "$site_dir" && pwd -P)
case $site_dir in
    *:*) die "the site directory's path contains a colon, which Docker cannot mount: $site_dir" 2 ;;
esac

# --- The Docker socket ------------------------------------------------------

# On Docker Desktop and OrbStack the daemon is in a VM, and the socket to
# mount is the one inside it, at the default path, whatever the host-side
# path of the context's socket is. On Linux it is the socket the client uses.
socket=/var/run/docker.sock
if [[ $host_os == Linux ]]; then
    endpoint=${DOCKER_HOST:-$(docker context inspect --format '{{.Endpoints.docker.Host}}' 2>/dev/null || printf '')}
    case $endpoint in
        unix://*) socket=${endpoint#unix://} ;;
        '') ;;
        *)
            die "Docker is configured to use a remote daemon ($endpoint).
  ghost-docker mounts the site directory into its manager, and a remote daemon
  would look for that directory on the other machine. Use a local daemon."
            ;;
    esac
    [[ -S $socket ]] || die "the Docker socket was not found at $socket."
fi

# --- A bundle to import, or a backup to restore --------------------------------
#
# Mounted read-only, at its own resolved absolute path, like the site
# directory, unless it is inside the site, which is mounted already. A path
# that does not exist is passed on as given, for the manager to report.
declare -a bundle_mount=()
bundle=${bundle_at:+${args[bundle_at]}}
if [[ -n $bundle && -e $bundle ]]; then
    if [[ -d $bundle ]]; then
        bundle=$(CDPATH='' cd -- "$bundle" && pwd -P)
    else
        bundle="$(CDPATH='' cd -- "$(dirname -- "$bundle")" && pwd -P)/$(basename -- "$bundle")"
    fi
    case $bundle/ in
        "$site_dir"/*) ;;
        *) bundle_mount=(--volume "$bundle:$bundle:ro") ;;
    esac
    args[bundle_at]=$bundle
fi

# --- Which image ------------------------------------------------------------

# Empty when this script is being read from a pipe (`curl ... | bash`): there is
# no file, so there is no checkout to find beside it.
script_dir=""
if [[ -n ${BASH_SOURCE[0]:-} && -f ${BASH_SOURCE[0]} ]]; then
    script_dir=$(CDPATH='' cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd -P)
fi
source_kind=image
# A channel is a tag that moves, and `docker run` would otherwise keep using
# whichever copy of it this host pulled first. Docker's progress goes to
# stderr, so a long pull is visibly happening. A release's tag never moves,
# so the copy this host has is the release.
declare -a pull=()
# The channel the manager records for the site, when a channel chose the image.
resolved_channel=""
use_channel() {
    resolved_channel=$1
    image="$GD_REGISTRY_IMAGE:$1"
    pull=(--pull always)
}
if [[ -n ${GD_IMAGE:-} ]]; then
    image=$GD_IMAGE
elif [[ -n $release ]]; then
    image="$GD_REGISTRY_IMAGE:$release"
elif [[ -n $channel ]]; then
    use_channel "$channel"
elif [[ -n $GD_PINNED_IMAGE && ${args[0]:-} == self-update ]]; then
    # The updater is the release being updated to, never the one the site runs.
    use_channel "${GD_PINNED_CHANNEL:-beta}"
elif [[ -n $GD_PINNED_IMAGE ]]; then
    image=$GD_PINNED_IMAGE
elif [[ -n $script_dir && -f $script_dir/manager/Dockerfile && -f $script_dir/compose.yml ]]; then
    # A checkout of the repository: build the manager from it. Docker's build
    # cache makes this quick when nothing has changed.
    source_kind=checkout
    image=ghost-docker:checkout
    # The commit it was built from, for `version` and `doctor` to report.
    commit=$(git -C "$script_dir" rev-parse HEAD 2>/dev/null || printf '')
    if ! build_output=$(docker build --quiet \
        --file "$script_dir/manager/Dockerfile" \
        --build-arg "GD_VERSION=checkout" --build-arg "GD_COMMIT=$commit" \
        --tag "$image" "$script_dir" 2>&1); then
        printf '%s\n' "$build_output" >&2
        die "the manager image could not be built from $script_dir."
    fi
else
    use_channel "${GD_CHANNEL:-beta}"
fi

# --- Run it -----------------------------------------------------------------

declare -a run=(
    docker run --rm --init ${pull[@]+"${pull[@]}"}
    --volume "$socket:/var/run/docker.sock"
    --volume "$site_dir:$site_dir"
    --workdir "$site_dir"
    --env "GD_SITE_DIR=$site_dir"
    --env "GD_UID=$(id -u)"
    --env "GD_GID=$(id -g)"
    --env "GD_ROOTLESS=$rootless"
    --env "GD_HOST_OS=$host_os"
    --env "GD_IMAGE=$image"
    --env "GD_SOURCE=$source_kind"
    # The socket as the daemon names it, for services that mount it themselves:
    # the upgrade supervisor.
    --env "GD_HOST_SOCKET=$socket"
)
[[ -z $resolved_channel ]] || run+=(--env "GD_CHANNEL=$resolved_channel")
[[ -z ${NO_COLOR:-} ]] || run+=(--env "NO_COLOR=$NO_COLOR")
[[ -z ${TERM:-} ]] || run+=(--env "TERM=$TERM")
# Keep a failed import's site for inspection instead of removing it (docs/install.md).
[[ -z ${GD_IMPORT_KEEP_FAILED:-} ]] || run+=(--env "GD_IMPORT_KEEP_FAILED=$GD_IMPORT_KEEP_FAILED")
run+=(${bundle_mount[@]+"${bundle_mount[@]}"})

# A terminal is attached when there is one, including when this script was
# piped from curl and stdin is therefore the script itself.
if [[ -t 0 && -t 1 ]]; then
    run+=(--interactive --tty)
    exec "${run[@]}" "$image" ${args[@]+"${args[@]}"}
elif [[ -t 1 ]] && (exec </dev/tty) 2>/dev/null; then
    run+=(--interactive --tty)
    exec "${run[@]}" "$image" ${args[@]+"${args[@]}"} </dev/tty
else
    exec "${run[@]}" "$image" ${args[@]+"${args[@]}"} </dev/null
fi
