#!/usr/bin/env bash
# Update the Growbud Edge Server on this computer (Linux).
#
#   sudo growbud-edge-update [--allow-downgrade] [VERSION]
#       Download the latest version (or VERSION) from the download site,
#       verify it, and run the installer with --yes. The installer backs
#       up the databases first (README section 8). The output goes to
#       update.log in the install folder.
#
# The Growbud desktop app runs this command through pkexec from its
# "Edge Server software" card. Environment:
#   GROWBUD_EDGE_BASE_URL  download site (default https://growbud.io/edge)
#   GROWBUD_EDGE_DIR       install folder
#
# install.sh puts a copy in /usr/local/sbin with the install folder filled
# in below.
set -euo pipefail

EDGE_DIR="${GROWBUD_EDGE_DIR:-@EDGE_DIR@}"
case "$EDGE_DIR" in
    @*@) EDGE_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" ;;
esac
BASE_URL="${GROWBUD_EDGE_BASE_URL:-https://growbud.io/edge}"
LOG="$EDGE_DIR/update.log"

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

sha256() {
    if command -v sha256sum >/dev/null 2>&1; then
        sha256sum "$1" | cut -d' ' -f1
    else
        shasum -a 256 "$1" | cut -d' ' -f1
    fi
}

# Download install.sh to a file, check it against install.sh.sha256 when the
# download site lists one, then run it. A wrong checksum stops the update.
# No checksum file: run it as before, with a warning.
run_installer() {
    local work
    work="$(mktemp -d)"
    # shellcheck disable=SC2064 # expand now: work is local
    trap "rm -rf '$work'" RETURN
    curl -fsSL --retry 3 -o "$work/install.sh" "$BASE_URL/install.sh" \
        || { echo "ERROR: could not download $BASE_URL/install.sh" >&2; return 1; }
    if curl -fsSL --retry 3 -o "$work/install.sh.sha256" "$BASE_URL/install.sh.sha256" 2>/dev/null; then
        local want got
        want="$(cut -d' ' -f1 < "$work/install.sh.sha256" | tr -d '[:space:]')"
        got="$(sha256 "$work/install.sh")"
        if [ -z "$want" ] || [ "$want" != "$got" ]; then
            echo "ERROR: install.sh SHA-256 mismatch: expected ${want:-nothing}, got $got. Nothing was changed." >&2
            return 1
        fi
        echo "install.sh SHA-256 OK"
    else
        echo "WARNING: $BASE_URL/install.sh.sha256 not found: install.sh was not checked."
    fi
    bash "$work/install.sh" --yes
}

main() {
    local allow_downgrade=0
    if [ "${1:-}" = --allow-downgrade ]; then
        allow_downgrade=1
        shift
    fi
    local version="${1:-}"
    [ "$(uname -s)" = Linux ] || fail "This command is for Linux."
    [ "$(id -u)" = 0 ] || fail "Run this command with sudo: sudo growbud-edge-update"
    [ -f "$EDGE_DIR/docker-compose.yml" ] && [ -f "$EDGE_DIR/.env" ] \
        || fail "The Edge Server is not installed in $EDGE_DIR."
    case "$version" in
        *[!0-9A-Za-z.-]*) fail "Invalid version: $version" ;;
    esac
    command -v curl >/dev/null 2>&1 || fail "curl is not installed."

    # pkexec starts with an empty environment: give the tools a PATH.
    export PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
    export GROWBUD_EDGE_DIR="$EDGE_DIR"
    export GROWBUD_EDGE_BASE_URL="$BASE_URL"
    [ -n "$version" ] && export GROWBUD_EDGE_VERSION="$version"
    # The installer refuses an older version unless told otherwise.
    [ "$allow_downgrade" = 1 ] && export GROWBUD_EDGE_ALLOW_DOWNGRADE=1

    if ! {
        printf '\n==== %s growbud-edge-update %s\n' "$(date -u '+%Y-%m-%dT%H:%M:%SZ')" "${version:-latest}"
        run_installer
    } > >(tee -a "$LOG") 2>&1 </dev/null; then
        fail "The update did not finish. See $LOG"
    fi
    local installed
    installed="$(tr -d '[:space:]' < "$EDGE_DIR/VERSION" 2>/dev/null || true)"
    [ -n "$installed" ] || fail "The update did not finish. See $LOG"
    if [ -n "$version" ] && [ "$installed" != "$version" ]; then
        fail "The update did not finish: $installed is installed, not $version. See $LOG"
    fi
    echo "Growbud Edge $installed is installed."
}

if [ "${BASH_SOURCE[0]}" = "$0" ]; then
    main "$@"
fi
