#!/bin/sh
#
# curl -fsSL https://get.lodol.com | sh
#
# The whole first-run experience is this script plus a URL, and every line it
# prints is part of the product. It asks nothing, offers no options, and ends
# with one address to open.
#
# Two things it deliberately does not do.
#
# It does not ask for a port. The web app inlines its API origin when it is
# built, so a chosen port would mean rebuilding the app on every machine — but
# the better reason is that nobody installing automation software wants to make
# that decision.
#
# It does not print any secrets. The signing key it generates lives in the
# config file; the key that encrypts credentials lives in the OS keychain, which
# already backs itself up and is a far better place for it than a terminal
# somebody will scroll past. Printing them would be a worse backup than where
# they already are, and one more thing to worry about at the moment the product
# should feel effortless.

set -eu

# Everything below is one compound command, so that a download which arrives
# only half-way runs none of it.
#
# This script is meant to be piped into sh. A shell reading from a pipe executes
# each command as soon as it has parsed one — so a connection dropped midway
# through would leave a machine that has downloaded a release, unpacked part of
# it, and registered nothing, with an exit status of 0 to say so. A brace group
# cannot be executed until its closing brace has been read, so a truncated
# download is a parse error that runs nothing and exits non-zero.
{

LODOL_VERSION="${LODOL_VERSION:-latest}"
LODOL_RELEASES="${LODOL_RELEASES:-https://get.lodol.com/releases}"

# Whether Lodol should look for new versions once a day.
#
# Empty means nobody said, which is not the same as "yes" and is why the two
# are kept apart: an installation that already has an answer keeps it, and
# only one given out loud this time overrules it. The setup program on
# Windows sets this when its checkbox is cleared, so unticking the box always
# takes effect, and leaving it ticked never switches checking back on for
# somebody who turned it off.
UPDATE_CHECK_ASKED="${LODOL_UPDATE_CHECK:-}"
case "$(printf '%s' "$UPDATE_CHECK_ASKED" | tr '[:upper:]' '[:lower:]')" in
    off|no|false|0) UPDATE_CHECK="off" ;;
    *) UPDATE_CHECK="on" ;;
esac

# The runtimes Lodol runs on, pinned so that every installation of a given
# version is the same installation. Fetched from the people who make them rather
# than packaged by us — MongoDB is SSPL, and the surest way not to have an
# argument about redistributing somebody else's software is not to redistribute
# it. Bumping any of these is a release decision, not a user's.
PYTHON_VERSION="3.13"
NODE_VERSION="24.21.0"
MONGODB_VERSION="8.0.4"
MONGOSH_VERSION="2.3.8"
MONGO_TOOLS_VERSION="100.10.0"

# Fetched to a temporary place first so a half-downloaded release can never
# become a half-installed one.
WORK="$(mktemp -d 2>/dev/null || mktemp -d -t lodol)"
cleanup() { rm -rf "$WORK"; }
trap cleanup EXIT INT TERM

# ── Helpers, until the real ones are unpacked ─────────────────────────────

if [ -t 1 ] && [ -z "${NO_COLOR:-}" ]; then
    _dim=$(printf '\033[2m'); _bold=$(printf '\033[1m')
    _red=$(printf '\033[31m'); _yellow=$(printf '\033[33m')
    _reset=$(printf '\033[0m')
else
    _dim=''; _bold=''; _red=''; _yellow=''; _reset=''
fi

# A step prints its name and then waits on the same line for its outcome, so
# anything that speaks before that outcome arrives has to close the line first
# or its message runs into "  Fetching MongoDB… ". Tracked here rather than
# remembered at each call site. Same arrangement as lib/common.sh, which takes
# over the moment the release is unpacked.
_step_open=""
_close_step() {
    [ -n "$_step_open" ] || return 0
    _step_open=""
    printf '\n'
}

say()  { _close_step; printf '%s\n' "$*"; }
step() { _step_open=1; printf '  %s… ' "$*"; }
done_() { _step_open=""; printf '%sdone%s\n' "$_dim" "$_reset"; }
warn() { _close_step; printf '%s⚠ %s%s\n' "$_yellow" "$*" "$_reset" >&2; }
die() {
    _close_step
    printf '\n%s✗ %s%s\n' "$_red" "$1" "$_reset" >&2
    shift
    [ $# -gt 0 ] && printf '\n%s\n' "$*" >&2
    exit 1
}

# Put a file in place by writing beside it and renaming, never by writing over
# it. `lodol update` runs from $LODOL_HOME/bin/lodol, and the shell executing
# that file reads it as it goes — so overwriting it mid-update makes the next
# read land at the same offset in different text, and the shell runs whatever
# fragment it finds there. A rename gives the new file its own inode and leaves
# the running process with the one it opened. Same reason `current` is switched
# with `mv` rather than written in place.
install_file() {
    _dest="$2"
    _tmp="$_dest.new.$$"
    cp "$1" "$_tmp"
    chmod "$3" "$_tmp"
    mv -f "$_tmp" "$_dest"
}

LODOL_HOME="${LODOL_DATA_DIR:-$HOME/.lodol}"
UPDATING="${LODOL_UPDATING:-}"

# ── Is this machine one we support? ───────────────────────────────────────

case "$(uname -s)" in
    Darwin) PLATFORM=macos ;;
    Linux)  PLATFORM=linux ;;
    *)
        die "Lodol does not run on $(uname -s)." \
            "Lodol Local supports macOS, Linux and Windows. On Windows, use
PowerShell instead:

    irm https://get.lodol.com/install.ps1 | iex"
        ;;
esac

case "$(uname -m)" in
    x86_64|amd64)  ARCH=x86_64 ;;
    arm64|aarch64) ARCH=arm64 ;;
    *)
        die "Lodol does not have a build for $(uname -m)." \
            "Lodol Local ships for 64-bit Intel and ARM. If you need this
architecture, tell us at support@lodol.com. It helps us decide what to build."
        ;;
esac

# Some of the Python packages the server needs publish ready-built copies only
# for recent macOS: ONNX Runtime and pymssql need 14 on Apple Silicon, and
# pymssql needs 15 on Intel. On anything older the install would try to build
# them from source and fail half-way, so say so before downloading anything.
# A version this cannot read is let through rather than refused.
if [ "$PLATFORM" = macos ]; then
    case "$ARCH" in
        arm64) MACOS_NEEDED=14 ;;
        *)     MACOS_NEEDED=15 ;;
    esac
    MACOS_VERSION="$(sw_vers -productVersion 2>/dev/null || true)"
    MACOS_MAJOR="${MACOS_VERSION%%.*}"
    case "$MACOS_MAJOR" in
        ''|*[!0-9]*) ;;
        *)
            [ "$MACOS_MAJOR" -ge "$MACOS_NEEDED" ] || die \
                "Lodol needs macOS $MACOS_NEEDED or later on this Mac, and it has macOS $MACOS_VERSION." \
                "Lodol Local runs on macOS 14 or later on Apple Silicon Macs, and
macOS 15 or later on Intel Macs. Update macOS from System Settings, under
General, Software Update, then run this again."
            ;;
    esac
fi

for tool in curl tar; do
    command -v "$tool" >/dev/null 2>&1 || die \
        "Lodol's installer needs $tool, and this machine does not have it." \
        "Install $tool and run this again."
done

# ── Is anything in the way? ───────────────────────────────────────────────

# See lib/common.sh for why this tries three things. The installer carries its
# own copy because it runs before anything is unpacked.
port_busy() {
    if command -v nc >/dev/null 2>&1; then
        nc -z 127.0.0.1 "$1" >/dev/null 2>&1
    elif command -v bash >/dev/null 2>&1; then
        bash -c "exec 3<>/dev/tcp/127.0.0.1/$1" >/dev/null 2>&1
    else
        curl -fsS --max-time 2 -o /dev/null "telnet://127.0.0.1:$1" >/dev/null 2>&1
    fi
}

if [ -z "$UPDATING" ]; then
    for port in 3900 3901 3902; do
        if port_busy "$port"; then
            # Being specific matters here: "port in use" sends somebody hunting,
            # and the usual culprit is the last Lodol, still running.
            if curl -fsS --max-time 2 -o /dev/null "http://localhost:3900" 2>/dev/null; then
                die "Lodol is already running on this machine." \
                    "Open http://localhost:3900, or update it with:

    lodol update"
            fi
            die "Something is already using port $port, which Lodol needs." \
                "Lodol uses ports 3900-3902 and cannot be moved to others.
Stop whatever is on port $port and run this again.

To find it:  lsof -nP -iTCP:$port -sTCP:LISTEN"
        fi
    done
fi

# ── Fetch ─────────────────────────────────────────────────────────────────

say ""
if [ -n "$UPDATING" ]; then
    say "${_bold}Updating Lodol${_reset}"
else
    say "${_bold}Installing Lodol${_reset}"
fi
say ""

step "Finding the latest version"
if [ "$LODOL_VERSION" = "latest" ]; then
    LODOL_VERSION="$(curl -fsSL "$LODOL_RELEASES/latest.txt" 2>/dev/null | tr -d ' \n\r')" || true
    [ -n "$LODOL_VERSION" ] || die \
        "Could not reach the Lodol download server." \
        "Check this machine is online, then run the command again. If you are
behind a proxy, Lodol's installer uses curl and honours https_proxy."
fi
done_

# Already on it, and this is `lodol update` rather than a fresh run of the
# installer. Downloading and unpacking what is already here would restart a
# working installation to arrive back where it started. A plain re-run of the
# installer is left alone: that is how somebody repairs a broken copy.
if [ -n "$UPDATING" ] && [ -L "$LODOL_HOME/current" ] && \
   [ "$(basename "$(readlink "$LODOL_HOME/current")")" = "$LODOL_VERSION" ]; then
    say ""
    say "Lodol $LODOL_VERSION is the latest version. Nothing to do."
    exit 0
fi

TARBALL="lodol-$LODOL_VERSION-$PLATFORM-$ARCH.tar.gz"
step "Downloading Lodol $LODOL_VERSION"
curl -fsSL "$LODOL_RELEASES/$LODOL_VERSION/$TARBALL" -o "$WORK/$TARBALL" || die \
    "Could not download Lodol $LODOL_VERSION for $PLATFORM ($ARCH)." \
    "The download server may be having a moment. Try again shortly."
done_

step "Checking it arrived intact"
if curl -fsSL "$LODOL_RELEASES/$LODOL_VERSION/$TARBALL.sha256" -o "$WORK/sum" 2>/dev/null; then
    expected="$(cut -d' ' -f1 <"$WORK/sum")"
    if command -v shasum >/dev/null 2>&1; then
        actual="$(shasum -a 256 "$WORK/$TARBALL" | cut -d' ' -f1)"
    else
        actual="$(sha256sum "$WORK/$TARBALL" | cut -d' ' -f1)"
    fi
    [ "$expected" = "$actual" ] || die \
        "The download does not match its checksum, so it was not installed." \
        "This usually means the download was interrupted. Try again.
If it keeps happening, tell us at support@lodol.com. We would want to know."
else
    # No checksum published for this release: say so rather than pretending the
    # check passed. Silence here would be the wrong kind of quiet.
    printf '%sno checksum published%s\n' "$_dim" "$_reset"
fi
[ -n "${actual:-}" ] && done_

# ── Unpack ────────────────────────────────────────────────────────────────

step "Unpacking"
DESTINATION="$LODOL_HOME/versions/$LODOL_VERSION"
mkdir -p "$DESTINATION" "$LODOL_HOME/logs" "$LODOL_HOME/data" "$LODOL_HOME/run"
tar -xzf "$WORK/$TARBALL" -C "$DESTINATION" --strip-components=1
done_


# ── The runtimes ──────────────────────────────────────────────────────────
#
# Everything lands inside this version's own directory, so two installed
# versions never share a runtime and removing one removes all of it.

fetch_python() {
    step "Setting up Python"
    # uv installs a standalone CPython that runs from wherever it is put, and
    # works out the right build for this machine itself — a great deal less to
    # get wrong than assembling download URLs for four platforms.
    if ! command -v uv >/dev/null 2>&1; then
        mkdir -p "$DESTINATION/uv"
        curl -fsSL https://astral.sh/uv/install.sh \
            | UV_INSTALL_DIR="$DESTINATION/uv" UV_NO_MODIFY_PATH=1 sh >/dev/null 2>&1
    fi
    UV="$(command -v uv 2>/dev/null || echo "$DESTINATION/uv/uv")"
    [ -x "$UV" ] || die \
        "Could not install uv, which Lodol uses to set up Python." \
        "Check this machine is online and run the installer again."

    # Made afresh every time. An earlier run that stopped after this step (the
    # keychain check, a dropped download) left one behind, and uv refuses to
    # create a virtual environment over another: the run the failure message
    # asked for then failed here, every time, with "Could not set up Python".
    # Removed rather than passed --clear, which an older uv on PATH lacks.
    rm -rf "$DESTINATION/python"
    "$UV" venv --python "$PYTHON_VERSION" --python-preference only-managed \
        --relocatable "$DESTINATION/python" >/dev/null 2>&1 || die \
        "Could not set up Python $PYTHON_VERSION." \
        "Run the installer again. If it keeps failing, tell us at
support@lodol.com."

    # What uv says goes to a log rather than the screen, and a failure points
    # at it. Saying "network problem" without looking hid the real reason the
    # last time one failed (a package with no build for Intel Macs).
    mkdir -p "$LODOL_HOME/logs"
    INSTALL_LOG="$LODOL_HOME/logs/install.log"
    "$UV" pip install --python "$DESTINATION/python/bin/python" \
        --requirement "$DESTINATION/server/requirements.txt" >>"$INSTALL_LOG" 2>&1 || die \
        "Could not install the Python packages Lodol needs." \
        "What went wrong is at the end of $INSTALL_LOG.
If this machine was offline, running the installer again will fix it.
Otherwise, send that file to support@lodol.com."

    # The Code step's extra packages, pinned and hashed, in a directory of
    # their own beside the interpreter rather than in it: a step that could
    # see the server's virtualenv would see every one of its dependencies.
    # Left writable, so `lodol update` and uninstall can remove it like the
    # rest of a version; on Linux the sandbox binds it read-only for each step.
    "$UV" pip install --python "$DESTINATION/python/bin/python" \
        --require-hashes --no-deps --compile-bytecode \
        --target "$DESTINATION/sandbox-packages" \
        --requirement "$DESTINATION/server/sandbox-requirements.txt" >>"$INSTALL_LOG" 2>&1 || die \
        "Could not install the packages Lodol's code step offers." \
        "What went wrong is at the end of $INSTALL_LOG.
If this machine was offline, running the installer again will fix it.
Otherwise, send that file to support@lodol.com."

    # And Lodol itself. Not optional plumbing: without it the server cannot
    # import its own package, and the version everything reports — /version,
    # lodol doctor, the update check — comes from this package's metadata.
    "$UV" pip install --python "$DESTINATION/python/bin/python" \
        --no-deps "$DESTINATION/server" >/dev/null 2>&1 || die \
        "Could not install Lodol's server package." \
        "Run the installer again. If it keeps failing, tell us at
support@lodol.com."
    done_
}

fetch_node() {
    step "Setting up Node"
    case "$PLATFORM-$ARCH" in
        macos-arm64)  node_build="darwin-arm64" ;;
        macos-x86_64) node_build="darwin-x64" ;;
        linux-arm64)  node_build="linux-arm64" ;;
        *)            node_build="linux-x64" ;;
    esac
    archive="node-v$NODE_VERSION-$node_build.tar.gz"
    curl -fsSL "https://nodejs.org/dist/v$NODE_VERSION/$archive" -o "$WORK/$archive" \
        || die "Could not download Node $NODE_VERSION." \
               "Check this machine is online and run the installer again."
    mkdir -p "$DESTINATION/node"
    tar -xzf "$WORK/$archive" -C "$DESTINATION/node" --strip-components=1
    # Headers and docs, needed only to compile native modules against this
    # Node. The web app ships already built, so nothing here ever will.
    rm -rf "$DESTINATION/node/include" "$DESTINATION/node/share" \
           "$DESTINATION/node/CHANGELOG.md" "$DESTINATION/node/README.md"
    done_
}

# MongoDB publishes no generic Linux build — only per-distribution ones. The
# builds are glibc-linked and an older baseline runs happily on a newer system,
# so an unrecognised distribution gets the oldest supported Ubuntu build rather
# than a refusal: a working database on Arch beats "your distribution is not on
# our list".
mongo_build_name() {
    if [ "$PLATFORM" = macos ]; then
        [ "$ARCH" = arm64 ] && echo "macos-arm64" || echo "macos-x86_64"
        return
    fi
    cpu="x86_64"
    [ "$ARCH" = arm64 ] && cpu="aarch64"

    distro=""
    # Reset first: this sources a file that sets these, and a value inherited
    # from the environment (or left behind by an earlier call) would otherwise
    # decide which build a machine gets.
    ID=""
    VERSION_ID=""
    # Which file says what this distribution is. Overridable so the URL test can
    # put every case through this function rather than hand-writing the URLs it
    # exists to check.
    os_release="${LODOL_OS_RELEASE:-/etc/os-release}"
    if [ -r "$os_release" ]; then
        # shellcheck disable=SC1090,SC1091  # a data file, not a script of ours
        . "$os_release"
        case "${ID:-}${VERSION_ID:-}" in
            ubuntu24*|ubuntu25*)          distro="ubuntu2404" ;;
            ubuntu22*|ubuntu23*)          distro="ubuntu2204" ;;
            debian12*|debian13*)          distro="debian12" ;;
            rhel9*|rocky9*|almalinux9*|centos9*) distro="rhel93" ;;
            amzn2023*)                    distro="amazon2023" ;;
        esac
    fi

    # Not every distribution is built for every processor — Debian, for one, is
    # x86 only. An ARM machine running one of those takes the Ubuntu build,
    # which exists and works, rather than a 404 most of the way through an
    # install. test-download-urls.sh is what keeps this list honest.
    if [ "$cpu" = aarch64 ]; then
        case "$distro" in
            ubuntu2404|ubuntu2204|rhel93|amazon2023) ;;
            *) distro="" ;;
        esac
    fi

    echo "linux-$cpu-${distro:-ubuntu2204}-$MONGODB_VERSION"
}

# The whole address, not just the build name. MongoDB's own path for macOS is
# "osx" rather than "macos" — theirs to name, not ours to guess — and the
# version sits in a different part of the name there than it does on Linux.
# Assembled in one function so install/test-download-urls.sh can ask the real
# server about every address this can produce, rather than about addresses
# somebody wrote out a second time.
mongo_download_url() {
    build="$(mongo_build_name)"
    if [ "$PLATFORM" = macos ]; then
        echo "https://fastdl.mongodb.org/osx/mongodb-$build-$MONGODB_VERSION.tgz"
    else
        echo "https://fastdl.mongodb.org/linux/mongodb-$build.tgz"
    fi
}

fetch_mongodb() {
    step "Setting up the database"
    url="$(mongo_download_url)"
    archive="${url##*/}"
    curl -fsSL "$url" -o "$WORK/$archive" \
        || die "Could not download MongoDB $MONGODB_VERSION." \
               "Check this machine is online and run the installer again."
    mkdir -p "$DESTINATION/mongodb"
    tar -xzf "$WORK/$archive" -C "$DESTINATION/mongodb" --strip-components=1

    # The shell ships separately. Lodol needs it once, to turn the fresh
    # database into a single-node replica set — which is not a preference: the
    # application uses transactions, and MongoDB offers those only on a set.
    case "$PLATFORM-$ARCH" in
        macos-arm64)  shell_build="darwin-arm64"; shell_ext="zip" ;;
        macos-x86_64) shell_build="darwin-x64";   shell_ext="zip" ;;
        linux-arm64)  shell_build="linux-arm64";  shell_ext="tgz" ;;
        *)            shell_build="linux-x64";    shell_ext="tgz" ;;
    esac
    shell_archive="mongosh-$MONGOSH_VERSION-$shell_build.$shell_ext"
    curl -fsSL "https://downloads.mongodb.com/compass/$shell_archive" \
        -o "$WORK/$shell_archive" \
        || die "Could not download the MongoDB shell." \
               "Lodol needs it once, to prepare the database. Try again shortly."
    if [ "$shell_ext" = zip ]; then
        (cd "$WORK" && unzip -qo "$shell_archive")
    else
        tar -xzf "$WORK/$shell_archive" -C "$WORK"
    fi
    found="$(find "$WORK" -name mongosh -type f -perm -u+x 2>/dev/null | head -1)"
    [ -n "$found" ] || die \
        "The MongoDB shell did not unpack as expected." \
        "Please tell us at support@lodol.com. This one is on us to fix."
    cp "$found" "$DESTINATION/mongodb/bin/mongosh"

    # mongodump, which the server runs before every schema migration so that a
    # bad update is recoverable. It moved out of the server download in
    # MongoDB 6, so without this the backup silently never happens — the code
    # treats a failed backup as non-fatal, which is right, but it would mean
    # nobody ever actually has one.
    case "$PLATFORM-$ARCH" in
        macos-arm64)  tools_build="macos-arm64";    tools_ext="zip" ;;
        macos-x86_64) tools_build="macos-x86_64";   tools_ext="zip" ;;
        linux-arm64)  tools_build="ubuntu2404-arm64"; tools_ext="tgz" ;;
        *)            tools_build="ubuntu2204-x86_64"; tools_ext="tgz" ;;
    esac
    tools_archive="mongodb-database-tools-$tools_build-$MONGO_TOOLS_VERSION.$tools_ext"
    if curl -fsSL "https://fastdl.mongodb.org/tools/db/$tools_archive" \
        -o "$WORK/$tools_archive" 2>/dev/null; then
        if [ "$tools_ext" = zip ]; then
            (cd "$WORK" && unzip -qo "$tools_archive")
        else
            tar -xzf "$WORK/$tools_archive" -C "$WORK"
        fi
        dump="$(find "$WORK" -name mongodump -type f -perm -u+x 2>/dev/null | head -1)"
        [ -n "$dump" ] && cp "$dump" "$DESTINATION/mongodb/bin/mongodump"
    fi
    [ -x "$DESTINATION/mongodb/bin/mongodump" ] || warn \
        "Could not install mongodump, so Lodol cannot back up your database
  before a schema change. Everything else works. Running the installer again
  later will pick it up."

    # Things a single-machine installation will never run. mongos routes
    # queries across a sharded cluster, and install_compass fetches a GUI that
    # is not ours to offer — together a third of the download, kept nowhere.
    rm -f "$DESTINATION/mongodb/bin/mongos" \
          "$DESTINATION/mongodb/bin/install_compass"
    done_
}

check_keyring() {
    # Lodol keeps saved credentials encrypted under a key in the OS keychain and
    # refuses to write them any other way — so a machine without one cannot run
    # it. macOS and Windows always have a keychain; Linux needs a Secret Service
    # provider, which desktops have and bare servers usually do not.
    #
    # Checked here, at second thirty, rather than left for the server to
    # discover: finishing with "installed!" and leaving something that will not
    # start is worse than not finishing.
    [ "$PLATFORM" = macos ] && return 0

    step "Checking this machine can store credentials safely"
    if LODOL_PROFILE=local "$DESTINATION/python/bin/python" -c \
        'import sys, keyring
backend = type(keyring.get_keyring()).__module__
sys.exit(1 if "fail" in backend or "null" in backend else 0)' >/dev/null 2>&1; then
        done_
        return 0
    fi
    die "This machine has nowhere safe to keep your credentials." \
        "Lodol encrypts saved credentials under a key in your keychain, and
will not write them any other way. Linux provides that through a Secret
Service, which desktops have and bare servers often do not.

On Debian or Ubuntu:

    sudo apt install gnome-keyring

On Fedora or RHEL:

    sudo dnf install gnome-keyring

Then run this installer again. Everything downloaded so far is kept, so it
will be quick."
}

# The installer's own fast tests check the refusals, the layout and what
# uninstall deletes — none of which need a runtime, and all of which would take
# minutes rather than seconds if they downloaded 400 MB first. That the
# downloads themselves are right is checked by test-download-urls.sh, against
# the real servers.
if [ -z "${LODOL_SKIP_RUNTIMES:-}" ]; then
    fetch_python
    fetch_node
    fetch_mongodb
    # After Python, because it is Python's keyring library that knows what this
    # machine can do — and before anything is switched on, so the answer arrives
    # as a clear refusal rather than as a server that will not start.
    check_keyring
fi

step "Setting up the commands"
mkdir -p "$LODOL_HOME/bin" "$LODOL_HOME/lib"
install_file "$DESTINATION/install/lib/common.sh" "$LODOL_HOME/lib/common.sh" 644
install_file "$DESTINATION/install/lib/doctor.sh" "$LODOL_HOME/lib/doctor.sh" 644
install_file "$DESTINATION/install/lodol" "$LODOL_HOME/bin/lodol" 755
install_file "$DESTINATION/install/lodol-run" "$LODOL_HOME/bin/lodol-run" 755

# The window, where the release carries one. Asked of the release rather than
# of `uname`: the archive for a platform that has one holds it and the one for
# a platform that does not holds nothing, so there is one rule here instead of
# a second copy of that decision.
if [ -x "$DESTINATION/window/Lodol" ]; then
    rm -rf "$LODOL_HOME/window"
    cp -R "$DESTINATION/window" "$LODOL_HOME/window"
    chmod 755 "$LODOL_HOME/window/Lodol"
fi

done_

# ── The lodol command, in any terminal ────────────────────────────────────
#
# Everything above works by full path, but every step anybody is given after
# installing begins `lodol`, and a fresh terminal answered "command not found".
# So a first install adds Lodol's bin directory to the PATH, the way rustup,
# uv and bun do, and says which files it changed:
#
#   - one block, between `# >>> lodol >>>` and `# <<< lodol <<<`, which
#     `lodol uninstall` takes out again;
#   - only in startup files that already exist, plus the one the person's own
#     shell reads if it has none. Never ~/.bash_profile beside an existing
#     ~/.profile: bash reads only the first of the two, so creating it would
#     quietly stop ~/.profile working;
#   - not on an update, so a line somebody took out stays out;
#   - not at all with LODOL_NO_MODIFY_PATH=1, or when `lodol` already runs.
#
# Windows does the same in install.ps1, with the user's own PATH variable.
PATH_BLOCK_START="# >>> lodol >>>"
PATH_BLOCK_END="# <<< lodol <<<"

# The directory as a shell should write it: $HOME/.lodol/bin when it is the
# usual place, so the line still reads right if the home directory moves.
path_entry() {
    if [ "$LODOL_HOME" = "$HOME/.lodol" ]; then
        # shellcheck disable=SC2016  # written for the shell to expand, later
        printf '%s' '$HOME/.lodol/bin'
    else
        printf '%s' "$LODOL_HOME/bin"
    fi
}

# Append the block to $1, unless it is already there. What is written is shell
# for the startup file to run, so its $PATH and $HOME stay unexpanded here.
# shellcheck disable=SC2016,SC2094
add_path_block() {
    _file="$1"
    _entry="$(path_entry)"
    if [ -f "$_file" ] && grep -qF "$PATH_BLOCK_START" "$_file" 2>/dev/null; then
        return 0
    fi
    {
        # A file that doesn't end in a newline would run its last line into ours.
        if [ -s "$_file" ] && [ -n "$(tail -c 1 "$_file")" ]; then
            printf '\n'
        fi
        printf '\n%s\n' "$PATH_BLOCK_START"
        printf '# The lodol command, added by its installer. `lodol uninstall` removes this.\n'
        if [ "${_file##*.}" = fish ]; then
            printf 'fish_add_path -g "%s"\n' "$_entry"
        else
            printf 'case ":$PATH:" in *":%s:"*) ;; *) export PATH="%s:$PATH" ;; esac\n' \
                "$_entry" "$_entry"
        fi
        printf '%s\n' "$PATH_BLOCK_END"
    } >>"$_file" 2>/dev/null || return 1
    # shellcheck disable=SC2088  # the ~ is shown to a person, not expanded
    case "$_file" in
        "$HOME"/*) _shown="~/${_file#"$HOME"/}" ;;
        *)         _shown="$_file" ;;
    esac
    PATH_FILES_CHANGED="$PATH_FILES_CHANGED    $_shown
"
}

add_lodol_to_path() {
    PATH_FILES_CHANGED=""
    case "$LODOL_HOME" in
        # A directory a shell would read differently from how it is written.
        *'"'*|*'$'*|*'`'*|*\\*) return 1 ;;
    esac
    _zshrc="${ZDOTDIR:-$HOME}/.zshrc"
    for _file in "$HOME/.profile" "$HOME/.bash_profile" "$HOME/.bash_login" \
                 "$HOME/.bashrc" "$_zshrc"; do
        if [ -f "$_file" ]; then add_path_block "$_file" || true; fi
    done
    # The person's own shell, if nothing above is a file it reads.
    case "$(basename "${SHELL:-}")" in
        zsh)
            [ -f "$_zshrc" ] || add_path_block "$_zshrc" || true
            ;;
        bash)
            if [ "$PLATFORM" = macos ]; then
                # Terminal on macOS starts a login shell, which reads the
                # first of these and only that one.
                if [ ! -f "$HOME/.bash_profile" ] && [ ! -f "$HOME/.bash_login" ] \
                    && [ ! -f "$HOME/.profile" ]; then
                    add_path_block "$HOME/.bash_profile" || true
                fi
            else
                [ -f "$HOME/.bashrc" ] || add_path_block "$HOME/.bashrc" || true
            fi
            ;;
        fish)
            { mkdir -p "$HOME/.config/fish/conf.d" 2>/dev/null &&
                add_path_block "$HOME/.config/fish/conf.d/lodol.fish"; } || true
            ;;
    esac
    [ -n "$PATH_FILES_CHANGED" ]
}

# Done here, with the commands, rather than at the end: an installation whose
# first start is slow stops before the end with "has not finished starting",
# and the steps it gives next are `lodol` commands too.
PATH_ADDED=""
if command -v lodol >/dev/null 2>&1; then
    PATH_ADDED=already
elif [ -z "$UPDATING" ] && [ -z "${LODOL_NO_MODIFY_PATH:-}" ] && add_lodol_to_path; then
    PATH_ADDED=yes
fi


# ── Configure ─────────────────────────────────────────────────────────────
#
# Written once and never regenerated: rotating the signing key on every update
# would log everybody out every time they updated.

if [ ! -f "$LODOL_HOME/config.env" ]; then
    step "Generating this installation's keys"
    # 24 random bytes as 48 hex characters. Read with a byte count rather than
    # by filtering an endless stream and cutting it short: `tr -dc … </dev/urandom
    # | head -c 48` only stops because head exits and tr is killed by SIGPIPE on
    # its next write, and a reader that never gets there never stops. `od -N`
    # reads exactly what it needs and the pipeline ends on its own.
    jwt_secret="$(
        LC_ALL=C od -An -tx1 -N 24 </dev/urandom 2>/dev/null | LC_ALL=C tr -d ' \n'
    )"
    # The database's password, made the same way. Hexadecimal, which matters
    # here: it goes inside a URI, and a character needing to be escaped there
    # is a connection string that silently means something else.
    mongo_pass="$(
        LC_ALL=C od -An -tx1 -N 24 </dev/urandom 2>/dev/null | LC_ALL=C tr -d ' \n'
    )"
    [ "${#mongo_pass}" -ge 32 ] || die \
        "Could not generate a secure key on this machine." \
        "Lodol needs /dev/urandom to create its database password. This is
unusual, so please tell us at support@lodol.com."
    [ "${#jwt_secret}" -ge 32 ] || die \
        "Could not generate a secure key on this machine." \
        "Lodol needs /dev/urandom to create its signing key. This is unusual, so
please tell us at support@lodol.com."
    # Narrowed to this one file and put back afterwards. Left set, it applied
    # to everything the installer created next — the icon, the desktop entry,
    # and on macOS the whole app bundle, which in /Applications means another
    # user on the machine sees an icon they cannot open.
    _previous_umask="$(umask)"
    umask 077
    # Every value quoted. The database URI contains an "&", which a shell
    # sourcing this file would read as "run everything before me in the
    # background" — silently losing the setting and leaving the server
    # reporting that a URI sitting right there on disk is missing.
    cat >"$LODOL_HOME/config.env" <<CONFIG
# Written by the Lodol installer. Safe to read, not safe to share.
# Updates never rewrite this file.
JWT_SECRET_KEY="$jwt_secret"
MONGO_URI="mongodb://lodol:$mongo_pass@127.0.0.1:3902/automation?replicaSet=lodol&directConnection=true&authSource=admin"
WEB_APP_DOMAIN="http://localhost:3900"
LODOL_PROFILE="local"

# If this machine reaches the internet through your organisation's proxy, say
# so here and run \`lodol restart\`. LODOL_EXTRA_CA_CERTS is for a proxy that
# inspects TLS: your organisation's root certificate, trusted as well as the
# usual ones.
# HTTPS_PROXY="http://proxy.example.com:8080"
# HTTP_PROXY="http://proxy.example.com:8080"
# NO_PROXY="intranet.example.com,.corp.example.com"
# LODOL_EXTRA_CA_CERTS="/path/to/root-ca.pem"
CONFIG
    chmod 600 "$LODOL_HOME/config.env"
    umask "$_previous_umask"
    done_

elif grep -q '^MONGO_URI=' "$LODOL_HOME/config.env" &&
     ! grep -q '^MONGO_URI="mongodb://[^:/]*:[^@]*@' "$LODOL_HOME/config.env"; then
    # An installation from before the database had a password. The server on
    # this machine was reachable by every other account signed in to it; it
    # gets a password now, and `lodol-run` creates the account to match on the
    # next start.
    #
    # One line is rewritten and the rest of the file is copied through
    # untouched. Regenerating it would rotate JWT_SECRET_KEY and sign
    # everybody out of an installation that was only being updated.
    step "Giving the database a password"
    mongo_pass="$(
        LC_ALL=C od -An -tx1 -N 24 </dev/urandom 2>/dev/null | LC_ALL=C tr -d ' \n'
    )"
    [ "${#mongo_pass}" -ge 32 ] || die \
        "Could not generate a secure key on this machine." \
        "Lodol needs /dev/urandom to create its database password. This is
unusual, so please tell us at support@lodol.com."

    old_uri="$(sed -n 's/^MONGO_URI="\(.*\)"$/\1/p' "$LODOL_HOME/config.env")"
    # The password is hexadecimal, so it needs no escaping on the way into
    # either the URI or this substitution.
    new_uri="$(printf '%s' "$old_uri" | sed "s|^mongodb://|mongodb://lodol:$mongo_pass@|")"
    case "$new_uri" in
        *authSource=*) ;;
        *) new_uri="$new_uri&authSource=admin" ;;
    esac

    _previous_umask="$(umask)"
    umask 077
    # awk rather than sed for the line itself: the URI contains an "&", which
    # sed would read as "the whole text that just matched".
    awk -v line="MONGO_URI=\"$new_uri\"" \
        '/^MONGO_URI=/ { print line; next } { print }' \
        "$LODOL_HOME/config.env" >"$LODOL_HOME/config.env.new"
    chmod 600 "$LODOL_HOME/config.env.new"
    mv -f "$LODOL_HOME/config.env.new" "$LODOL_HOME/config.env"
    umask "$_previous_umask"
    done_
fi

# ── Whether to look for new versions ──────────────────────────────────────
#
# Written here rather than with the keys above so that there is one copy of
# it, reached by a fresh install and by an installation from before Lodol
# looked for new versions alike. Appended, never a rewrite of the file: the
# rest of it is this installation's identity, and regenerating it would sign
# everybody out of something that was only being updated.
#
# The comment goes in with it. Somebody who wants this off will open this
# file, and finding the answer there is the difference between a setting and
# a thing they have to search for.
_update_check_set=""
_previous_umask="$(umask)"
umask 077
if [ -n "$UPDATE_CHECK_ASKED" ] &&
   grep -q '^LODOL_UPDATE_CHECK=' "$LODOL_HOME/config.env"; then
    awk -v line="LODOL_UPDATE_CHECK=\"$UPDATE_CHECK\"" \
        '/^LODOL_UPDATE_CHECK=/ { print line; next } { print }' \
        "$LODOL_HOME/config.env" >"$LODOL_HOME/config.env.new"
    chmod 600 "$LODOL_HOME/config.env.new"
    mv -f "$LODOL_HOME/config.env.new" "$LODOL_HOME/config.env"
    _update_check_set=1
elif ! grep -q '^LODOL_UPDATE_CHECK=' "$LODOL_HOME/config.env"; then
    cat >>"$LODOL_HOME/config.env" <<CONFIG

# Whether Lodol looks for new versions once a day. Set it to "off" to stop.
# Nothing else changes: Lodol never installs an update on its own either way.
LODOL_UPDATE_CHECK="$UPDATE_CHECK"
CONFIG
    _update_check_set=1
fi
umask "$_previous_umask"

# Said once, when the answer is first written or changed, and not on every
# update afterwards. Starting to make a daily request from somebody's machine
# without telling them would be the wrong way round, and telling them again
# every time they update would be noise about a thing they already settled.
if [ -n "$_update_check_set" ]; then
    if [ "$UPDATE_CHECK" = "on" ]; then
        say "  ${_dim}Lodol will look for new versions once a day. It never installs one${_reset}"
        say "  ${_dim}on its own, and sends nothing about you or your machine.${_reset}"
    else
        say "  ${_dim}Lodol will not look for new versions.${_reset}"
    fi
fi

# ── Somewhere to click ────────────────────────────────────────────────────
#
# The install used to end by printing a URL. Once that window was closed there
# was nothing on the machine that led back to Lodol, and nothing but a terminal
# command to stop it — which is fine for somebody who installed it by pasting a
# curl line, and a dead end for everybody else.
#
# Both entries run `lodol open`, not the URL: a bookmark to localhost:3900 is
# dead while Lodol is stopped, and this starts it first.

step "Adding Lodol to your applications"
icons="$DESTINATION/icons"
shortcuts="$DESTINATION/install/shortcuts"
if [ "$PLATFORM" = macos ]; then
    # /Applications when this user may write there, ~/Applications otherwise.
    # Both are searched by Spotlight and shown in Launchpad; neither needs sudo,
    # which the rest of this installer does not ask for either.
    #
    # Overridable for the same reason LODOL_DATA_DIR is: this is the one thing
    # left that writes outside the installation, and the tests must not put an
    # app bundle in a real /Applications on somebody's Mac.
    # Make it before asking whether we can write to it. On a real Mac
    # /Applications is already there, but anywhere else the directory is ours
    # to create, and -w on a path that does not exist yet is false -- which
    # sent every such install to ~/Applications instead.
    apps="${LODOL_APPLICATIONS:-/Applications}"
    mkdir -p "$apps" 2>/dev/null || true
    if [ ! -w "$apps" ]; then
        apps="$HOME/Applications"
        mkdir -p "$apps"
    fi
    app="$apps/Lodol.app"
    rm -rf "$app"
    mkdir -p "$app/Contents/MacOS" "$app/Contents/Resources"
    sed -e "s|__LODOL_VERSION__|$LODOL_VERSION|g" \
        "$shortcuts/Info.plist" >"$app/Contents/Info.plist"
    sed -e "s|__LODOL_HOME__|$LODOL_HOME|g" \
        "$shortcuts/launcher.sh" >"$app/Contents/MacOS/Lodol"
    chmod +x "$app/Contents/MacOS/Lodol"
    [ -f "$icons/lodol.icns" ] && cp "$icons/lodol.icns" "$app/Contents/Resources/lodol.icns"
    # Tell the Finder the bundle changed, or it keeps showing the old icon.
    touch "$app"
else
    [ -f "$icons/lodol.png" ] && cp "$icons/lodol.png" "$LODOL_HOME/lodol.png"
    entries="$HOME/.local/share/applications"
    mkdir -p "$entries"
    sed -e "s|__LODOL_HOME__|$LODOL_HOME|g" \
        "$shortcuts/lodol.desktop" >"$entries/lodol.desktop"
    # Best effort: menus pick the file up on next login without it.
    command -v update-desktop-database >/dev/null 2>&1 &&
        update-desktop-database "$entries" >/dev/null 2>&1
fi
done_

# ── Make it start at login ────────────────────────────────────────────────

# Installing a launchd agent or a systemd unit touches the machine outside
# $LODOL_DATA_DIR — the one thing in this script that does. The installer's own
# tests set this so that running them cannot leave a real background service
# behind on a developer's laptop pointed at a temporary directory.
if [ -n "${LODOL_SKIP_SERVICE:-}" ]; then
    say "  ${_dim}Not registering a background service (LODOL_SKIP_SERVICE).${_reset}"
else

step "Setting Lodol to start when you log in"
if [ "$PLATFORM" = macos ]; then
    agents="$HOME/Library/LaunchAgents"
    mkdir -p "$agents"
    sed "s|__LODOL_HOME__|$LODOL_HOME|g" \
        "$DESTINATION/install/agents/com.lodol.server.plist" \
        >"$agents/com.lodol.server.plist"
    launchctl bootout "gui/$(id -u)/com.lodol.server" >/dev/null 2>&1 || true
    launchctl bootstrap "gui/$(id -u)" "$agents/com.lodol.server.plist" >/dev/null 2>&1 || true
else
    units="$HOME/.config/systemd/user"
    mkdir -p "$units"
    sed "s|__LODOL_HOME__|$LODOL_HOME|g" \
        "$DESTINATION/install/agents/lodol.service" >"$units/lodol.service"
    systemctl --user daemon-reload >/dev/null 2>&1 || true
    systemctl --user enable lodol.service >/dev/null 2>&1 || true
fi
done_

fi

# ── Switch to it ──────────────────────────────────────────────────────────
#
# The symlink flip is the moment the new version becomes the running one. Doing
# it last means an install that fails halfway leaves the previous version
# untouched and still working.

step "Starting Lodol"
PREVIOUS_VERSION=""
if [ -L "$LODOL_HOME/current" ]; then
    PREVIOUS_VERSION="$(basename "$(readlink "$LODOL_HOME/current")")"
fi
# `ln -sfn`, not a rename over the top. `mv` follows a destination symlink that
# points at a directory, so moving the new link onto `current` moved it *into*
# the version `current` pointed at — leaving `current` on the old version and a
# stray `current.new` inside it. Every update unpacked a new version and went
# on running the previous one; the line below this used to be the moment that
# was supposed to stop being true.
#
# `-n` is the whole reason this works: without it `ln` follows the existing
# symlink for the same reason `mv` did.
ln -sfn "$DESTINATION" "$LODOL_HOME/current"

# Everything older than the one now running and the one it replaced. Each of
# those directories is a whole CPython, Node and MongoDB — several hundred
# megabytes that nothing will ever run again — and nothing removed them, so a
# machine updated monthly grew by that much every month, forever.
#
# The version just replaced is kept, and only that one: it is the way back if
# this release turns out to be wrong, and it is named rather than guessed at
# from timestamps, so the answer cannot drift.
for old_version in "$LODOL_HOME"/versions/*; do
    [ -d "$old_version" ] || continue
    old_name="$(basename "$old_version")"
    [ "$old_name" = "$LODOL_VERSION" ] && continue
    [ "$old_name" = "$PREVIOUS_VERSION" ] && continue
    rm -rf "$old_version"
done

if [ -z "${LODOL_SKIP_SERVICE:-}" ]; then
    if [ "$PLATFORM" = macos ]; then
        launchctl kickstart -k "gui/$(id -u)/com.lodol.server" >/dev/null 2>&1 || true
    else
        systemctl --user restart lodol.service >/dev/null 2>&1 || true
    fi
fi

# Two minutes is generous: the first start migrates the database and warms the
# app. Overridable so the installer's own tests, which have nothing real to
# start, do not spend two minutes proving it.
start_timeout="${LODOL_START_TIMEOUT:-120}"
# Both halves: the page, and the server everything on it comes from. The page on
# its own came up while the server stopped on start, and this said "running".
web_up() { curl -fsS --max-time 2 -o /dev/null "http://localhost:3900" 2>/dev/null; }
server_up() { curl -fsS --max-time 2 -o /dev/null "http://localhost:3901/capabilities" 2>/dev/null; }
# Whether the page answered at any point. A server that stops on start takes the
# page down with it until the service restarts both, so at the moment this gives
# up the page may be down too, and "has not finished starting" would hide that
# the server was the half that never came up.
web_seen=""
waited=0
while [ "$waited" -lt "$start_timeout" ]; do
    if web_up; then
        web_seen=1
        server_up && break
    fi
    sleep 1
    waited=$((waited + 1))
done
if [ "$waited" -ge "$start_timeout" ]; then
    printf '\n'
    if [ -n "$web_seen" ]; then
        die "Lodol installed, but its server has not started." \
            "The page came up, but the server behind it never answered, so the
page would be empty. See why with:

    $LODOL_HOME/bin/lodol logs

and paste what it says to support@lodol.com if it is not clear."
    fi
    die "Lodol installed, but has not finished starting." \
        "It may still be coming up. Check with:

    $LODOL_HOME/bin/lodol status
    $LODOL_HOME/bin/lodol doctor"
fi
done_

# ── Tell them where it is ─────────────────────────────────────────────────

say ""
say "  ${_bold}Lodol is running at http://localhost:3900${_reset}"
say ""

# Where the lodol command is, now that it is running (see "The lodol command,
# in any terminal" above).
case "$PATH_ADDED" in
    already) ;;
    yes)
        say "  ${_dim}The 'lodol' command is ready in any new terminal. Added to:${_reset}"
        printf '%s' "${_dim}$PATH_FILES_CHANGED${_reset}"
        say "  ${_dim}In this terminal, run: export PATH=\"$(path_entry):\$PATH\"${_reset}"
        say ""
        ;;
    *)
        say "  ${_dim}To use the 'lodol' command from anywhere, add this to your shell:${_reset}"
        say "  ${_dim}  export PATH=\"$(path_entry):\$PATH\"${_reset}"
        say ""
        ;;
esac


}
