#!/usr/bin/env bash
# ============================================================================
#  LXRAY  -  Linux Diagnostic Collector & Analyzer
#  Collects a complete system snapshot (like sosreport) and analyses it into
#  a scored HTML report with actionable findings.
#
#  Usage:  lxray collect [options]
#          lxray analyze <snapshot-dir|snapshot.tar.gz> [options]
#          lxray run [options]
#          lxray plugins | version | help
# ============================================================================

LXD_APP="lxray"
# The analyzer must not write bytecode next to the installed files: an uninstall
# would leave a __pycache__ folder behind.
export PYTHONDONTWRITEBYTECODE=1

# Resolve install root (works through symlinks)
_lxd_self="$0"
while [ -L "$_lxd_self" ]; do
    _lxd_link="$(readlink "$_lxd_self" 2>/dev/null)" || break
    case "$_lxd_link" in
        /*) _lxd_self="$_lxd_link" ;;
        *)  _lxd_self="$(dirname "$_lxd_self")/$_lxd_link" ;;
    esac
done
LXD_ROOT="$(cd "$(dirname "$_lxd_self")/.." 2>/dev/null && pwd)"
[ -d "$LXD_ROOT/lib" ] || LXD_ROOT="/opt/lxray"

LXD_VERSION="$(head -n1 "$LXD_ROOT/VERSION" 2>/dev/null || echo unknown)"

# shellcheck source=/dev/null
. "$LXD_ROOT/lib/common.sh" 2>/dev/null || {
    echo "lxray: cannot load $LXD_ROOT/lib/common.sh" >&2
    exit 2
}

# shellcheck source=/dev/null
. "$LXD_ROOT/lib/compat.sh" 2>/dev/null || {
    echo "lxray: cannot load $LXD_ROOT/lib/compat.sh" >&2
    exit 2
}

# shellcheck source=/dev/null
. "$LXD_ROOT/lib/access.sh" 2>/dev/null || {
    echo "lxray: cannot load $LXD_ROOT/lib/access.sh" >&2
    exit 2
}

# ---------------------------------------------------------------------------
# Defaults
# ---------------------------------------------------------------------------
LXD_PROFILE="standard"
LXD_CMD_TIMEOUT=30
LXD_FILE_MAX=4194304
LXD_REDACT=1
LXD_REDACT_IPS=0
LXD_QUIET=0
LXD_ONLY=""
LXD_EXCLUDE=""
LXD_NO_TAR=0
LXD_NO_ANALYZE=0
LXD_OPEN_REPORT=0
LXD_DEPS_INSTALL=0

# Colours
if [ -t 1 ] && [ "${NO_COLOR:-}" = "" ] && [ "${TERM:-dumb}" != "dumb" ]; then
    LXD_COLOR=1
    C_BOLD=$'\033[1m'; C_DIM=$'\033[2m'; C_OFF=$'\033[0m'
    C_RED=$'\033[31m'; C_GREEN=$'\033[32m'; C_YELLOW=$'\033[33m'; C_CYAN=$'\033[36m'
else
    LXD_COLOR=0
    C_BOLD=""; C_DIM=""; C_OFF=""; C_RED=""; C_GREEN=""; C_YELLOW=""; C_CYAN=""
fi

# ---------------------------------------------------------------------------
# Help
# ---------------------------------------------------------------------------
usage() {
cat <<EOF
${C_BOLD:-}LXRAY ${LXD_VERSION}${C_OFF:-} - Linux diagnostic collector and analyzer

${C_BOLD:-}USAGE${C_OFF:-}
  lxray collect [options]           Collect a system snapshot
  lxray analyze <path> [options]    Analyse a snapshot (directory or .tar.gz)
  lxray run [options]               Collect + analyse in one step
  lxray deps [--install]            Show missing diagnostic tools, install them
  lxray plugins                     List collection plugins
  lxray version | help

${C_BOLD:-}COLLECT OPTIONS${C_OFF:-}
  -o, --outdir DIR      Output directory (default: /var/tmp)
  -p, --profile P       quick | standard | full        (default: standard)
      --timeout SEC     Per-command timeout             (default: 30)
      --only LIST       Comma separated plugin ids to run
      --exclude LIST    Comma separated plugin ids to skip
      --no-redact       Do not scrub secrets, MACs, UUIDs, emails
      --redact-ips      Also scrub IP addresses
      --no-tar          Keep the directory, do not create the tarball
      --no-analyze      Collect only, skip the report
  -q, --quiet           Minimal console output

${C_BOLD:-}ANALYZE OPTIONS${C_OFF:-}
  -o, --outdir DIR      Where to write the report (default: beside snapshot)
      --format LIST     html,md,json,txt                (default: html,md,json)
      --open            Try to open the report in a browser

${C_BOLD:-}EXAMPLES${C_OFF:-}
  lxray run                          # one-shot: snapshot + HTML report
  lxray collect -p full -o /tmp      # big snapshot, keep tarball
  lxray analyze /var/tmp/lxray-web01-20260101-1200.tar.gz

Exit codes: 0 ok, 1 error, 2 usage, 3 partial collection (run without root,
or a plugin failed): the report is written and lists what is missing
EOF
}

# ---------------------------------------------------------------------------
# Argument parsing
# ---------------------------------------------------------------------------
MODE=""
TARGET=""
FORMATS="html,md,json"

set_profile() {
    case "$1" in
        quick)    LXD_PROFILE=quick;    LXD_CMD_TIMEOUT=${LXD_CMD_TIMEOUT_OVERRIDE:-10}; LXD_FILE_MAX=524288 ;;
        standard) LXD_PROFILE=standard; LXD_CMD_TIMEOUT=${LXD_CMD_TIMEOUT_OVERRIDE:-30}; LXD_FILE_MAX=4194304 ;;
        full)     LXD_PROFILE=full;     LXD_CMD_TIMEOUT=${LXD_CMD_TIMEOUT_OVERRIDE:-60}; LXD_FILE_MAX=16777216 ;;
        *) echo "lxray: unknown profile '$1' (quick|standard|full)" >&2; exit 2 ;;
    esac
}

while [ $# -gt 0 ]; do
    case "$1" in
        collect|analyze|run|plugins|version|help|deps|-h|--help)
            if [ -z "$MODE" ]; then MODE="$1"; else TARGET="$1"; fi
            shift ;;
        -o|--outdir)      LXD_OUTDIR="$2"; shift 2 ;;
        -p|--profile)     set_profile "$2"; shift 2 ;;
        --timeout)        LXD_CMD_TIMEOUT_OVERRIDE="$2"; LXD_CMD_TIMEOUT="$2"; shift 2 ;;
        --only)           LXD_ONLY="$2"; shift 2 ;;
        --exclude)        LXD_EXCLUDE="$2"; shift 2 ;;
        --no-redact)      LXD_REDACT=0; shift ;;
        --redact-ips)     LXD_REDACT_IPS=1; shift ;;
        --no-tar)         LXD_NO_TAR=1; shift ;;
        --no-analyze)     LXD_NO_ANALYZE=1; shift ;;
        --format)         FORMATS="$2"; shift 2 ;;
        --open)           LXD_OPEN_REPORT=1; shift ;;
        --install)        LXD_DEPS_INSTALL=1; shift ;;
        -q|--quiet)       LXD_QUIET=1; shift ;;
        -*)               echo "lxray: unknown option '$1'" >&2; exit 2 ;;
        *)                [ -z "$TARGET" ] && TARGET="$1" || { echo "lxray: unexpected argument '$1'" >&2; exit 2; }; shift ;;
    esac
done

[ -z "$MODE" ] && MODE="help"

case "$MODE" in
    help|-h|--help) usage; exit 0 ;;
    version) echo "lxray $LXD_VERSION"; exit 0 ;;
esac

# ---------------------------------------------------------------------------
# Plugin listing
# ---------------------------------------------------------------------------
list_plugins() {
    local f id title
    printf '%-22s %s\n' "ID" "DESCRIPTION"
    printf '%-22s %s\n' "--" "-----------"
    for f in "$LXD_ROOT"/plugins/*.sh; do
        [ -e "$f" ] || continue
        id="$(basename "$f" .sh)"
        title="$(sed -n '2s/^# lxray-plugin: [^|]*| *//p' "$f" 2>/dev/null)"
        printf '%-22s %s\n' "$id" "$title"
    done
}

if [ "$MODE" = "plugins" ]; then list_plugins; exit 0; fi

# ---------------------------------------------------------------------------
# DEPS mode - what is missing on this flavour, and how to install it
# ---------------------------------------------------------------------------
if [ "$MODE" = "deps" ]; then
    lxd_detect_caps
    echo "${C_BOLD:-}LXRAY dependency check${C_OFF:-}"
    printf '  %-12s %s\n' "platform" "$(lxd_distro_pretty)"
    printf '  %-12s %s\n' "family"   "$LXD_FAMILY"
    printf '  %-12s %s\n' "pkg mgr"  "$LXD_PKG"
    printf '  %-12s %s\n' "init"     "$LXD_INIT"
    echo
    printf '%-18s %-12s %-9s %s\n' "GROUP" "PROBE" "STATUS" "WHAT IT UNLOCKS"
    printf '%-18s %-12s %-9s %s\n' "-----" "-----" "------" "----------------"
    PKGS=""
    while IFS= read -r line; do
        [ -z "$line" ] && continue
        group="${line%%:*}"; rest="${line#*:}"
        probe="${rest%%:*}"; desc="${rest#*:}"
        if lxd_have "$probe"; then
            printf '%-18s %-12s %-9s %s\n' "$group" "$probe" "ok" "$desc"
        else
            printf '%-18s %-12s %-9s %s\n' "$group" "$probe" "MISSING" "$desc"
            p="$(lxd_pkg_name "$group" "$LXD_FAMILY")"
            if [ -n "$p" ]; then
                case " $PKGS " in *" $p "*) ;; *) PKGS="$PKGS $p" ;; esac
            fi
        fi
    done <<EOF
$LXD_TOOL_GROUPS
EOF

    PKGS="$(echo $PKGS)"
    echo
    if [ -z "$PKGS" ]; then
        lxd_ok "all diagnostic tools are installed"
        exit 0
    fi
    lxd_warn "missing packages:$PKGS"
    echo "  install with: ${C_BOLD:-}$(lxd_install_cmd $PKGS)${C_OFF:-}"
    if [ "$LXD_DEPS_INSTALL" = "1" ]; then
        if ! lxd_is_root; then
            echo "lxray: --install requires root" >&2
            exit 1
        fi
        echo
        lxd_log "installing..."
        sh -c "$(lxd_install_cmd $PKGS)" || { echo "installation failed" >&2; exit 1; }
    else
        echo "  or run: lxray deps --install"
    fi
    exit 0
fi

# ---------------------------------------------------------------------------
# ANALYZE mode
# ---------------------------------------------------------------------------
if [ "$MODE" = "analyze" ]; then
    [ -z "$TARGET" ] && { echo "lxray: analyze needs a snapshot path" >&2; exit 2; }
    [ -e "$TARGET" ] || { echo "lxray: no such file or directory: $TARGET" >&2; exit 1; }
    PY="$(command -v python3 || command -v python)"
    if [ -z "$PY" ]; then
        echo "lxray: python3 is required for analysis (collection works without it)" >&2
        exit 1
    fi
    _openflag=""
    [ "$LXD_OPEN_REPORT" = "1" ] && _openflag="--open"
    "$PY" "$LXD_ROOT/analyzer/lxray_analyze.py" "$TARGET" \
        ${LXD_OUTDIR:+--outdir "$LXD_OUTDIR"} \
        --formats "$FORMATS" $_openflag
    exit $?
fi

# ---------------------------------------------------------------------------
# COLLECT mode
# ---------------------------------------------------------------------------
HOST="$(hostname 2>/dev/null | cut -d. -f1 || echo linux)"
HOST="${HOST:-linux}"
STAMP="$(lxd_ts)"
OUTBASE="${LXD_OUTDIR:-/var/tmp}"
mkdir -p "$OUTBASE" 2>/dev/null || { echo "lxray: cannot write to $OUTBASE" >&2; exit 1; }
LXD_OUT="$OUTBASE/lxray-$HOST-$STAMP"
mkdir -p "$LXD_OUT" 2>/dev/null || { echo "lxray: cannot create $LXD_OUT" >&2; exit 1; }

: >"$LXD_OUT/.plugins.tsv"
: >"$LXD_OUT/commands.log"

lxd_detect_caps
lxd_write_caps
lxd_access_check

START_EPOCH=$(date +%s)

lxd_banner "LXRAY $LXD_VERSION - snapshot of $(lxd_distro_pretty)"
lxd_log "  ${C_DIM:-}host${C_OFF:-}     $HOST"
lxd_log "  ${C_DIM:-}kernel${C_OFF:-}   $(lxd_kernel) ($(lxd_arch))"
lxd_log "  ${C_DIM:-}flavour${C_OFF:-}  ${LXD_FAMILY} family / ${LXD_PKG} / ${LXD_INIT} / ${LXD_NET_TOOL} / fw=${LXD_FW_BACKEND}"
lxd_log "  ${C_DIM:-}profile${C_OFF:-}  $LXD_PROFILE  (timeout ${LXD_CMD_TIMEOUT}s/command)"
lxd_log "  ${C_DIM:-}output${C_OFF:-}   $LXD_OUT"
# grep, not awk: this count decides the exit code and must not depend on a
# tool that may be missing
LXD_GAPS="$(grep -v '^privileges' "$LXD_OUT/access.tsv" 2>/dev/null | grep -cE "$(printf '\t')(missing|partial)$(printf '\t')")"
LXD_GAPS="${LXD_GAPS:-0}"
for _t in awk sed grep find sort; do
    lxd_have "$_t" || lxd_warn "core tool '$_t' is missing: many sections will be empty (install gawk/sed/grep/findutils/coreutils)"
done
if ! lxd_is_root; then
    lxd_warn "not running as root: $LXD_GAPS source(s) unreadable or partly readable, listed in the report"
    lxd_log  "    ${C_DIM:-}for a complete snapshot: sudo lxray run${C_OFF:-}"
fi
echo

# ---- plugin selection -----------------------------------------------------
want_plugin() {
    local id="$1" p
    if [ -n "$LXD_ONLY" ]; then
        case ",$LXD_ONLY," in *",$id,"*) : ;; *) return 1 ;; esac
    fi
    if [ -n "$LXD_EXCLUDE" ]; then
        case ",$LXD_EXCLUDE," in *",$id,"*) return 1 ;; esac
    fi
    # heavy plugins skipped in quick mode
    if [ "$LXD_PROFILE" = "quick" ]; then
        case "$id" in
            60-packages|85-databases|90-containers) return 1 ;;
        esac
    fi
    return 0
}

PLUGIN_COUNT=0
PLUGIN_FAILED=0

for _pf in "$LXD_ROOT"/plugins/*.sh; do
    [ -e "$_pf" ] || continue
    _pid="$(basename "$_pf" .sh)"
    want_plugin "$_pid" || continue

    _ptitle="$(sed -n '2s/^# lxray-plugin: [^|]*| *//p' "$_pf" 2>/dev/null)"
    [ -n "$_ptitle" ] || _ptitle="$_pid"

    lxd_plugin_start
    lxd_sec "$_pid" >/dev/null
    (
        LX_SEC="$LXD_OUT/$_pid"
        # shellcheck source=/dev/null
        . "$_pf"
    )
    _prc=$?
    PLUGIN_COUNT=$((PLUGIN_COUNT + 1))

    _pstatus="ok"
    if [ -f "$LXD_OUT/$_pid/.skipped" ]; then
        _pstatus="skipped"
    elif [ "$_prc" -ne 0 ]; then
        _pstatus="failed"
        PLUGIN_FAILED=$((PLUGIN_FAILED + 1))
    fi
    lxd_plugin_finish "$_pid" "$_ptitle" "$_pstatus"
done

# ---- manifest -------------------------------------------------------------
END_EPOCH=$(date +%s)
DURATION=$(( END_EPOCH - START_EPOCH ))
FILE_COUNT=$(find "$LXD_OUT" -type f 2>/dev/null | wc -l | tr -d ' ')
TOTAL_SIZE=$(du -sk "$LXD_OUT" 2>/dev/null | awk '{print $1*1024}'); [ -n "$TOTAL_SIZE" ] || TOTAL_SIZE=0

OS_ID="$(lxd_distro_id)"
OS_NAME="$(lxd_distro_pretty)"
KERNEL="$(lxd_kernel)"
ARCH="$(lxd_arch)"
VIRT="$(lxd_virt)"
CPUS="$(lxd_cpu_count)"
MEMKB="$(lxd_mem_total_kb)"
IPADDR="$(hostname -I 2>/dev/null | awk '{print $1}')"

{
    printf '{\n'
    printf '  "tool": "lxray",\n'
    printf '  "version": "%s",\n' "$LXD_VERSION"
    printf '  "schema": 1,\n'
    printf '  "started": "%s",\n' "$(date -d "@$START_EPOCH" '+%Y-%m-%dT%H:%M:%S%z' 2>/dev/null || date '+%Y-%m-%dT%H:%M:%S%z')"
    printf '  "finished": "%s",\n' "$(date -d "@$END_EPOCH" '+%Y-%m-%dT%H:%M:%S%z' 2>/dev/null || date '+%Y-%m-%dT%H:%M:%S%z')"
    printf '  "duration_s": %s,\n' "$DURATION"
    printf '  "profile": "%s",\n' "$LXD_PROFILE"
    printf '  "redact": %s,\n' "$([ "$LXD_REDACT" = 1 ] && echo true || echo false)"
    printf '  "redact_ips": %s,\n' "$([ "$LXD_REDACT_IPS" = 1 ] && echo true || echo false)"
    printf '  "as_root": %s,\n' "$(lxd_is_root && echo true || echo false)"
    printf '  "host": {\n'
    printf '    "hostname": "%s",\n' "$(printf '%s' "$HOST" | lxd_json_escape)"
    printf '    "fqdn": "%s",\n' "$(hostname -f 2>/dev/null | lxd_json_escape)"
    printf '    "ip": "%s",\n' "$(printf '%s' "$IPADDR" | lxd_json_escape)"
    printf '    "os_id": "%s",\n' "$(printf '%s' "$OS_ID" | lxd_json_escape)"
    printf '    "os_name": "%s",\n' "$(printf '%s' "$OS_NAME" | lxd_json_escape)"
    printf '    "kernel": "%s",\n' "$(printf '%s' "$KERNEL" | lxd_json_escape)"
    printf '    "arch": "%s",\n' "$(printf '%s' "$ARCH" | lxd_json_escape)"
    printf '    "virt": "%s",\n' "$(printf '%s' "$VIRT" | lxd_json_escape)"
    printf '    "cpus": %s,\n' "${CPUS:-0}"
    printf '    "mem_kb": %s\n' "${MEMKB:-0}"
    printf '  },\n'
    printf '  "collection": {\n'
    printf '    "files": %s,\n' "$FILE_COUNT"
    printf '    "size_bytes": %s,\n' "$TOTAL_SIZE"
    printf '    "plugins": [\n'
    _first=1
    while IFS=$'\t' read -r _id _title _status _dur; do
        [ -z "$_id" ] && continue
        [ "$_first" = "1" ] || printf ',\n'
        _first=0
        printf '      {"id": "%s", "title": "%s", "status": "%s", "duration": "%s"}' \
            "$(printf '%s' "$_id" | lxd_json_escape)" \
            "$(printf '%s' "$_title" | lxd_json_escape)" \
            "$_status" "$_dur"
    done <"$LXD_OUT/.plugins.tsv"
    printf '\n    ]\n'
    printf '  }\n'
    printf '}\n'
} >"$LXD_OUT/manifest.json" 2>/dev/null

# ---- human readable guide inside the snapshot -----------------------------
{
    echo "LXRAY SNAPSHOT"
    echo "==============="
    echo
    printf '%-12s %s\n' "host"      "$HOST"
    printf '%-12s %s\n' "collected" "$(date '+%Y-%m-%d %H:%M:%S %z')"
    printf '%-12s %s\n' "tool"      "lxray $LXD_VERSION"
    printf '%-12s %s\n' "profile"   "$LXD_PROFILE"
    printf '%-12s %s\n' "platform"  "$OS_NAME ($LXD_FAMILY family)"
    printf '%-12s %s\n' "kernel"    "$KERNEL ($ARCH)"
    printf '%-12s %s\n' "root"      "$(lxd_is_root && echo yes || echo no)"
    printf '%-12s %s\n' "pkg mgr"   "$LXD_PKG"
    printf '%-12s %s\n' "firewall"  "$LXD_FW_BACKEND"
    echo
    echo "LAYOUT"
    echo "------"
    printf '  %-20s %s\n' "capabilities.txt" "detected distribution, init system and tools"
    printf '  %-20s %s\n' "access.tsv"       "what this run could and could not read, and why"
    printf '  %-20s %s\n' "commands.log"     "every command executed, exit code and output file"
    printf '  %-20s %s\n' "manifest.json"    "machine readable metadata"
    printf '  %-20s %s\n' "checksums.sha256" "sha256 of every collected file"
    while IFS="$(printf '\t')" read -r _id _title _status _dur; do
        [ -z "$_id" ] && continue
        printf '  %-20s %s (%s, %s)\n' "$_id/" "$_title" "$_status" "$_dur"
    done <"$LXD_OUT/.plugins.tsv"
    echo
    echo "ANALYSE THIS SNAPSHOT"
    echo "---------------------"
    echo "  lxray analyze $LXD_OUT"
    echo
    echo "Collection is read-only: nothing on the host was modified. Secrets,"
    echo "MAC addresses, UUIDs and e-mail addresses are redacted at collection"
    echo "time unless --no-redact was given."
} >"$LXD_OUT/README.txt" 2>/dev/null

rm -f "$LXD_OUT/.plugins.tsv" 2>/dev/null

# ---- checksums ------------------------------------------------------------
( cd "$LXD_OUT" 2>/dev/null && find . -type f ! -name checksums.sha256 -print0 2>/dev/null \
    | xargs -0 sha256sum 2>/dev/null >checksums.sha256 ) 2>/dev/null || true

# ---- tarball --------------------------------------------------------------
TARBALL=""
if [ "$LXD_NO_TAR" = "0" ]; then
    TARBALL="$OUTBASE/lxray-$HOST-$STAMP.tar.gz"
    ( cd "$OUTBASE" && tar -czf "$TARBALL" "$(basename "$LXD_OUT")" 2>/dev/null )
    if [ -f "$TARBALL" ]; then
        lxd_ok "archive $(basename "$TARBALL") ($(du -h "$TARBALL" 2>/dev/null | awk '{print $1}'))"
    else
        TARBALL=""
        lxd_warn "could not create archive, keeping directory"
    fi
fi

lxd_banner "Collection finished in ${DURATION}s - $FILE_COUNT files"
[ "$PLUGIN_FAILED" -gt 0 ] && lxd_warn "$PLUGIN_FAILED plugin(s) reported errors (snapshot still usable)"

# ---- analyse --------------------------------------------------------------
RC=0
if [ "$LXD_NO_ANALYZE" = "0" ]; then
    PY="$(command -v python3 || command -v python)"
    if [ -n "$PY" ]; then
        echo
        lxd_banner "Analysis"
        _openflag=""
        [ "$LXD_OPEN_REPORT" = "1" ] && _openflag="--open"
        "$PY" "$LXD_ROOT/analyzer/lxray_analyze.py" "$LXD_OUT" --formats "$FORMATS" $_openflag
        RC=$?
    else
        lxd_warn "python3 not found - snapshot collected, report skipped"
        lxd_log "  ${C_DIM:-}install python3, then run: lxray analyze $LXD_OUT${C_OFF:-}"
        RC=3
    fi
else
    lxd_log "  ${C_DIM:-}analyse later with: lxray analyze $LXD_OUT${C_OFF:-}"
fi

echo
lxd_log "${C_BOLD:-}Snapshot:${C_OFF:-} $LXD_OUT"
[ -n "$TARBALL" ] && lxd_log "${C_BOLD:-}Archive :${C_OFF:-} $TARBALL"
[ -f "$LXD_OUT/report/lxray-report.html" ] && \
    lxd_log "${C_BOLD:-}Report  :${C_OFF:-} $LXD_OUT/report/lxray-report.html"

# 3 = partial collection: a plugin failed, or protected sources were unreadable
if [ "$RC" = "0" ]; then
    if [ "$PLUGIN_FAILED" -gt 0 ]; then RC=3; fi
    if ! lxd_is_root && [ "${LXD_GAPS:-0}" -gt 0 ]; then RC=3; fi
fi
exit "$RC"
