#!/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; }

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}"
        curl -fsSL --retry 3 "$BASE_URL/install.sh" | bash -s -- --yes
    } > >(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
