#!/bin/bash
################################################################################
# Script Name: version/3.7.3/UPDATE.sh
# Description: Apply version 3.7.3 - a patch release:
#              - the webmail no longer ships image parsers that a malformed
#                JXL, HEIF or ICNS file can make loop forever
#              - an account's CPU and memory are measured against a ceiling it
#                can actually reach, so a plan promising more than the server
#                has stops pinning every usage bar at nothing
#              - Delete on the notifications page acts on the notification the
#                administrator chose, not on whatever has moved into its place
#              - the thread-propagation UPDATE uses an index instead of
#                scanning every message the account owns
#              This script verifies the first and the last on this machine
#              rather than assuming the rebuild did them.
# Company/Brand: HiTechCloud by Pho Tue SoftWare Solutions JSC
################################################################################

set -uo pipefail
GREEN='\033[0;32m'; YELLOW='\033[1;33m'; RED='\033[0;31m'; NC='\033[0m'
ok()   { echo -e "[3.7.3] ${GREEN}✓${NC} $*"; }
warn() { echo -e "[3.7.3] ${YELLOW}!${NC} $*" >&2; }
bad()  { echo -e "[3.7.3] ${RED}✗${NC} $*" >&2; }
[[ $EUID -eq 0 ]] || { echo "[3.7.3] This update must run as root." >&2; exit 1; }

VERSION="3.7.3"
BIN=/usr/local/bin
WEBMAIL_SRC="${HITECHCLOUD_WEBMAIL_SRC:-/opt/hitechcloud/hitechcloudmail/webmail}"
DRY_RUN="${HITECHCLOUD_UPDATE_DRY_RUN:-0}"
run() { if [[ "$DRY_RUN" == 1 ]]; then echo "[3.7.3] would: $*"; else "$@"; fi; }

mkdir -p /usr/local/hitechcloud /etc/hitechcloud 2>/dev/null || true
echo "$VERSION" > /usr/local/hitechcloud/version 2>/dev/null || true
echo "$VERSION" > /etc/hitechcloud/version 2>/dev/null || true

# 1. The webmail's dependency tree.
#
#    image-size 1.2.1 to 2.0.2 can be driven into an infinite loop by a
#    malformed JXL, HEIF or ICNS file. The webmail backend reached it through
#    pptxgenjs, whose latest release still asks for the vulnerable range, so
#    this release pins it with an npm override.
#
#    An override only takes effect when node_modules is rebuilt. `hitechcloudcli
#    update` already calls `native-webmail update`, which runs `npm ci` - but a
#    server that applied this file by hand, or whose webmail rebuild failed
#    earlier and was not noticed, would still be running the old copy. So check
#    the version that is actually installed, and say so plainly when it is
#    still one of the vulnerable ones. A warning is the right level: the panel
#    works either way, and a failed exit here would strand the rest of the
#    update over a dependency.
if systemctl list-unit-files 2>/dev/null | grep -q '^hitechcloud-webmail\.service'; then
    installed_pkg="${WEBMAIL_SRC}/backend/node_modules/image-size/package.json"
    if [[ -f "$installed_pkg" ]]; then
        have=$(sed -n 's/.*"version"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' "$installed_pkg" | head -1)
        major=${have%%.*}
        if [[ -n "$major" && "$major" -ge 2 ]] && [[ "$have" != "2.0.0" && "$have" != "2.0.1" && "$have" != "2.0.2" ]]; then
            ok "webmail image parsers: image-size ${have}"
        else
            warn "the webmail still has image-size ${have}, which can be made to loop forever by a malformed JXL, HEIF or ICNS file. Run: hitechcloudcli native-webmail update"
        fi
    else
        run "${BIN}/hitechcloudcli" native-webmail update >/dev/null 2>&1 \
            && ok "webmail rebuilt from this release" \
            || warn "the webmail could not be rebuilt; run: hitechcloudcli native-webmail update"
    fi
fi

# 2. The thread-propagation index.
#
#    Shipped as webmail migration 0060 and applied by the webmail itself at
#    startup, so nothing here has to create it. What is worth doing is saying
#    whether it arrived: a CREATE INDEX CONCURRENTLY that failed leaves the
#    migration unrecorded and retried next boot, which is correct but silent,
#    and the symptom - every threaded arrival scanning the whole mailbox - is
#    invisible until somebody profiles the database.
if command -v psql >/dev/null 2>&1 && [[ -n "${WEBMAIL_DB_URL:-}" ]]; then
    if psql "${WEBMAIL_DB_URL}" -tAc \
        "SELECT 1 FROM pg_indexes WHERE tablename='messages' AND indexname='idx_messages_thread_id_all'" \
        2>/dev/null | grep -q 1; then
        ok "thread propagation index present"
    else
        warn "the thread propagation index is not there yet; the webmail creates it on its next start"
    fi
fi

# 3. Nothing to do for the other two. The usage collector and the admin panel
#    are binaries this release has already replaced; both changes are in their
#    own code and need no state migrated. Said here so that a reader of this
#    file is not left wondering which parts of the changelog it covers.
ok "usage measured against the reachable ceiling, and notifications named by content: carried by the binaries in this release"

ok "Version ${VERSION} applied."
