#!/bin/sh
# SPEC_712 PHASE C: the repo hygiene seed (SPEC_705's uninstall body
# merges into this file — ONE postrm per package, by dpkg's law).
# SPEC_714 PHASE F: this postrm is now the FULL uninstall executor — it
# reads the consent marker (OpenBloomData/uninstall.json, the SPEC_705
# Phase D declaration surface) and applies the declared purge, per user
# home carrying an instance. The fail-safe law: only a CLEAN read drives
# a deletion; anything unreadable or corrupt = the data is KEPT and the
# fact is logged. The postrm never prompts (dpkg's law), everything it
# does is logged to the removal output.
#
# The marker: { "purge_data": bool (default true), "purge_workspaces":
# bool (default false), "declared_at": ... }. An absent marker means the
# defaults. purge_data kills the instance data dir
# (~/.local/share/eu.openbloom.engine). purge_workspaces kills the
# registered workspace folders (the plaintext mirror the app maintains:
# OpenBloomData/uninstall-workspaces.json — the registry itself is
# vault-encrypted and unreadable root-side, by design).
set -e

SOURCES_LIST="/etc/apt/sources.list.d/openbloom.list"
KEYRING="/etc/apt/keyrings/openbloom.asc"
APP_DATA_PARENT="eu.openbloom.engine"
MIRROR_NAME="uninstall-workspaces.json"

log() {
    echo "openbloom-postrm: $*"
}

# Read a JSON bool field from a marker file WITHOUT jq (the deb has no jq
# dependency). A conservative grep: the app writes the marker itself,
# pretty-printed by serde. Anything absent or malformed = empty result
# and the caller applies the DEFAULT (the fail-safe law: only a clean
# read drives a deletion — for a MALFORMED marker, the code below keeps
# everything, the stricter direction).
read_bool_field() {
    # $1 = file, $2 = field
    sed -n "s/.*\"$2\"[[:space:]]*:[[:space:]]*\\(true\\|false\\).*/\\1/p" "$1" 2>/dev/null | head -n 1
}

apply_purge_for_home() {
    home="$1"
    instance_dir="$home/.local/share/$APP_DATA_PARENT"
    data_dir="$instance_dir/OpenBloomData"
    marker="$data_dir/uninstall.json"

    # No instance in this home: nothing to do.
    [ -d "$data_dir" ] || return 0

    log "instance found for ${home}: applying the uninstall declaration"

    purge_data=""
    purge_workspaces=""
    if [ -f "$marker" ]; then
        purge_data=$(read_bool_field "$marker" "purge_data")
        purge_workspaces=$(read_bool_field "$marker" "purge_workspaces")
        # A marker that exists but yields NO clean booleans is corrupt:
        # keep everything (the fail-safe law), log it.
        if [ -z "$purge_data" ] && [ -z "$purge_workspaces" ]; then
            log "WARNING: the uninstall marker is unreadable (${marker}); keeping all data (fail-safe)"
            return 0
        fi
    else
        log "no marker found; applying the defaults (purge data, keep workspaces)"
    fi

    # The defaults (SPEC_705): data purged, workspaces kept.
    [ "$purge_data" = "false" ] || purge_data="true"
    [ "$purge_workspaces" = "true" ] || purge_workspaces="false"

    if [ "$purge_workspaces" = "true" ]; then
        mirror="$data_dir/$MIRROR_NAME"
        if [ -f "$mirror" ]; then
            # The mirror: a JSON array of absolute paths (the app-maintained
            # mirror, pretty-printed by serde: one path per line). Every
            # path is validated to start with /home/ or /root/ before ANY
            # deletion: a malformed mirror line is skipped, never executed.
            sed -n 's/^ *"\(\/[^" ]*\)",\?$/\1/p' "$mirror" 2>/dev/null | while read -r ws_path; do
                case "$ws_path" in
                    /home/*|/root/*)
                        if [ -d "$ws_path" ]; then
                            log "purging the declared workspace folder: $ws_path"
                            rm -rf -- "$ws_path"
                        else
                            log "workspace folder already absent: $ws_path"
                        fi
                        ;;
                    *)
                        log "WARNING: skipping a mirror path outside the homes: $ws_path"
                        ;;
                esac
            done
        else
            log "WARNING: workspace purge declared but the mirror is missing (${mirror}); keeping the workspace folders (fail-safe)"
        fi
    else
        log "workspace purge not declared; the workspace folders are kept"
    fi

    if [ "$purge_data" = "true" ]; then
        log "purging the OpenBloom data (the declared default): $instance_dir"
        rm -rf -- "$instance_dir"
    else
        log "data purge not declared; the OpenBloom data is kept: $instance_dir"
    fi
}

# The repo hygiene (SPEC_712): purge removes the apt repo registration
# this package created; remove (non-purge) keeps it.
if [ "$1" = "purge" ]; then
    rm -f "$SOURCES_LIST" "$KEYRING"

    # SPEC_714 PHASE F — the declaration executor, per user home. The
    # postrm runs root-side with no user context: every home carrying an
    # instance gets its own marker applied.
    for home_dir in /root /home/*; do
        [ -d "$home_dir" ] || continue
        apply_purge_for_home "$home_dir"
    done
fi

exit 0
