#!/usr/bin/env bash
# =============================================================================
# onx-trash-empty — Permanently remove all soft-deleted items in ~/.trash/
#
# Purpose:
#   Wipes /home/<user>/.trash/* (skips the .trash root itself). Used by the
#   File Manager "Empty trash" action and by the 30-day cron auto-cleanup
#   (use {"older_than_days": 30} for that case).
#
# Input (stdin JSON):
#   {
#     "username":         "onx_xxxx",
#     "older_than_days":  null    -- optional; only wipe entries older than N days
#   }
#
# Output (stdout JSON):
#   {
#     "username":     "onx_xxxx",
#     "removed":      3,
#     "freed_bytes":  12894,
#     "remaining":    0
#   }
#
# Exit codes: 0=ok 1=invalid-input 2=preflight-fail 3=execution-fail
# Deployed to: /usr/local/onoxsoft/bin/onx-trash-empty
# =============================================================================

set -euo pipefail

SCRIPT_DIR="$(dirname "$(readlink -f "$0")")"
# shellcheck source=_lib/common.sh
source "${SCRIPT_DIR}/_lib/common.sh"

require_cmd jq

onx_json_input

USERNAME="$(onx_json_field username)"
OLDER_THAN="$(onx_json_field older_than_days "")"

onx_validate_username "$USERNAME"

HOME_DIR="/home/${USERNAME}"
TRASH_ROOT="${HOME_DIR}/.trash"

if [[ ! -d "${TRASH_ROOT}" ]]; then
    jq -nc --arg username "${USERNAME}" \
        '{username: $username, removed: 0, freed_bytes: 0, remaining: 0}'
    exit 0
fi

NOW_TS="$(date +%s)"
REMOVED=0
FREED_BYTES=0

shopt -s nullglob
for dir in "${TRASH_ROOT}"/*/; do
    [[ -d "${dir}" ]] || continue

    # Verify we're not somehow above .trash (defense in depth).
    case "${dir}" in
        "${TRASH_ROOT}"/*/) ;;
        *) continue ;;
    esac

    SIZE=0
    if [[ -f "${dir}/.meta.json" ]]; then
        SIZE="$(jq -r '.size_bytes // 0' "${dir}/.meta.json" 2>/dev/null || echo 0)"

        # Age filter.
        if [[ -n "${OLDER_THAN}" && "${OLDER_THAN}" != "null" && "${OLDER_THAN}" =~ ^[0-9]+$ ]]; then
            DELETED_AT="$(jq -r '.deleted_at // ""' "${dir}/.meta.json" 2>/dev/null || echo "")"
            DELETED_TS=0
            if [[ -n "${DELETED_AT}" ]]; then
                DELETED_TS="$(date -d "${DELETED_AT}" +%s 2>/dev/null || echo 0)"
            fi
            (( DELETED_TS > 0 )) || continue
            AGE_DAYS=$(( (NOW_TS - DELETED_TS) / 86400 ))
            (( AGE_DAYS > OLDER_THAN )) || continue
        fi
    else
        SIZE="$(du -sb "${dir}" 2>/dev/null | awk '{print $1}')"
    fi

    if rm -rf -- "${dir}" 2>/dev/null; then
        REMOVED=$(( REMOVED + 1 ))
        FREED_BYTES=$(( FREED_BYTES + ${SIZE:-0} ))
    fi
done
shopt -u nullglob

# Count remaining entries after deletion.
REMAINING=0
shopt -s nullglob
for d in "${TRASH_ROOT}"/*/; do
    [[ -d "${d}" ]] && REMAINING=$(( REMAINING + 1 ))
done
shopt -u nullglob

onx_log "trash-empty: user=${USERNAME} removed=${REMOVED} freed=${FREED_BYTES} remaining=${REMAINING}"

jq -nc \
    --arg username "${USERNAME}" \
    --argjson removed "${REMOVED}" \
    --argjson freed_bytes "${FREED_BYTES}" \
    --argjson remaining "${REMAINING}" \
    '{
        username: $username,
        removed: $removed,
        freed_bytes: $freed_bytes,
        remaining: $remaining
     }'
