#!/bin/sh
# Installs the `slate` command:
#
#   curl -fsSL https://labs.iaye.net/slate/install.sh | sh
#
# Checks Docker, downloads slate, verifies its SHA-256 and puts it in
# ~/.local/bin (SLATE_INSTALL_DIR). Running it again updates the command and
# never touches your environments.
#
# Settings (environment variables):
#   SLATE_VERSION      a release to install, e.g. 0.1.0 (default: the newest)
#   SLATE_INSTALL_DIR  where to put `slate` (default: ~/.local/bin)
#   SLATE_BASE_URL     where releases live (default: https://labs.iaye.net/slate)
# Options:
#   --from <file>      install this local copy of slate instead of downloading
#
# Everything is inside main(), called on the last line, so a download cut off
# halfway runs nothing.
set -eu

main() {
    base="${SLATE_BASE_URL:-https://labs.iaye.net/slate}"
    dir="${SLATE_INSTALL_DIR:-${HOME}/.local/bin}"
    from=''
    while [ "$#" -gt 0 ]; do
        case "$1" in
            --from) from="${2:?--from needs a file}"; shift ;;
            --from=*) from="${1#*=}" ;;
            -h|--help) sed -n '2,19p' "$0" 2>/dev/null | sed 's/^# \{0,1\}//'; return 0 ;;
            *) fail "Unknown option: $1" ;;
        esac
        shift
    done

    os="$(uname -s)"
    case "${os}" in
        Linux)
            if grep -qi microsoft /proc/version 2>/dev/null; then kind=wsl; else kind=linux; fi ;;
        Darwin) kind=macos ;;
        *) fail "Slate runs on Linux, macOS and Windows (inside WSL2); this is ${os}." ;;
    esac
    case "$(uname -m)" in
        x86_64|amd64|aarch64|arm64) ;;
        *) warn "Slate's images are built for amd64 and arm64; $(uname -m) isn't one of them." ;;
    esac

    docker_ok=1
    check_docker "${kind}"

    tmp="$(mktemp "${TMPDIR:-/tmp}/slate.XXXXXX")"
    trap 'rm -f "${tmp}"' EXIT INT TERM

    if [ -n "${from}" ]; then
        [ -f "${from}" ] || fail "No such file: ${from}"
        cp "${from}" "${tmp}"
    else
        if [ -n "${SLATE_VERSION:-}" ]; then
            url="${base}/slate-${SLATE_VERSION}"
            sum="$(fetch "${url}.sha256" | awk '{ print $1; exit }')" \
                || fail "Couldn't download ${url}.sha256. Is ${SLATE_VERSION} a release?"
            [ -n "${sum}" ] || fail "Couldn't download ${url}.sha256. Is ${SLATE_VERSION} a release?"
        else
            json="$(fetch "${base}/latest.json")" || fail "Couldn't reach ${base}/latest.json."
            url="$(printf '%s' "${json}" | json_str cli)"
            sum="$(printf '%s' "${json}" | json_str sha256)"
            if [ -z "${url}" ] || [ -z "${sum}" ]; then
                fail "${base}/latest.json is incomplete."
            fi
        fi
        fetch "${url}" > "${tmp}" || fail "Couldn't download ${url}."
        got="$(sha256_of "${tmp}")"
        [ "${got}" = "${sum}" ] || fail "Checksum mismatch for ${url} (expected ${sum}, got ${got}); nothing installed."
    fi
    head -n 1 "${tmp}" | grep -q '^#!/bin/sh' || fail "That doesn't look like the slate script."

    mkdir -p "${dir}"
    chmod 755 "${tmp}"
    # Same directory, then rename: a running `slate` never sees a half-written file.
    cp "${tmp}" "${dir}/.slate.new.$$"
    mv -f "${dir}/.slate.new.$$" "${dir}/slate"
    version="$("${dir}/slate" version 2>/dev/null || echo slate)"
    ok "Installed ${version} in ${dir}/slate"

    case ":${PATH}:" in
        *":${dir}:"*) ;;
        *)
            say ""
            say "  ${dir} isn't on your PATH. Add it:"
            case "${SHELL:-}" in
                */zsh)  say "    echo 'export PATH=\"${dir}:\$PATH\"' >> ~/.zshrc && exec zsh" ;;
                */fish) say "    fish_add_path ${dir}" ;;
                *)      say "    echo 'export PATH=\"${dir}:\$PATH\"' >> ~/.bashrc && exec bash" ;;
            esac ;;
    esac
    say ""
    if [ "${docker_ok}" = 1 ]; then
        say "  Next: slate new work"
    else
        say "  Next: slate setup    (installs or starts Docker; asks first)"
    fi
}

say()  { printf '%s\n' "$*"; }
ok()   { printf '✔ %s\n' "$*"; }
warn() { printf '! %s\n' "$*" >&2; }
fail() { printf '✘ %s\n' "$*" >&2; exit 1; }

have() { command -v "$1" >/dev/null 2>&1; }

fetch() {
    if have curl; then curl -fsSL "$1"
    elif have wget; then wget -qO- "$1"
    else fail "Need curl or wget."
    fi
}

sha256_of() {
    if have sha256sum; then sha256sum "$1" | cut -d' ' -f1
    elif have shasum; then shasum -a 256 "$1" | cut -d' ' -f1
    else fail "Need sha256sum or shasum to check the download."
    fi
}

json_str() {
    sed -n "s/.*\"$1\"[[:space:]]*:[[:space:]]*\"\\([^\"]*\\)\".*/\\1/p" | head -n 1
}

# Docker problems are warnings here: `slate` checks again before it does
# anything, and `slate setup` can install or start Docker afterwards.
check_docker() {
    if ! have docker; then
        warn "Docker isn't installed. Slate needs it:"
        docker_hint "$1"
        docker_ok=0
        return 0
    fi
    if ! docker info >/dev/null 2>&1; then
        warn "Docker is installed but not running (or you can't reach it):"
        docker_hint "$1"
        docker_ok=0
        return 0
    fi
    if ! docker compose version >/dev/null 2>&1; then
        warn "Docker Compose v2 (the 'docker compose' plugin) is missing; update Docker."
        docker_ok=0
        return 0
    fi
    ok "Docker $(docker version --format '{{.Server.Version}}' 2>/dev/null || true), Compose $(docker compose version --short 2>/dev/null || true)"
}

docker_hint() {
    case "$1" in
        macos) say "  Docker Desktop: https://docs.docker.com/desktop/setup/install/mac-install/ (OrbStack and Colima work too)" >&2 ;;
        wsl)   say "  Docker Desktop for Windows with WSL integration turned on for this distro:" >&2
               say "  https://docs.docker.com/desktop/features/wsl/" >&2 ;;
        *)     say "  https://docs.docker.com/engine/install/ — then: sudo systemctl start docker" >&2 ;;
    esac
}

main "$@"
