#!/usr/bin/env bash
# Export registered paths from an existing AIDE text database.
# Optionally correlate regular-file entries with the installed RPM database.
# Compatible with the standard text format used by AIDE 0.16 and 0.19.
# No AIDE integrity check or database update is performed.
# --sha-csv reads the current content of registered regular files.

export LC_ALL=C

PROG=${0##*/}
DB=/var/lib/aide/aide.db.gz
OUT=''
FILES_ONLY=0
RPM_MODE=0
SHA_CSV_MODE=0
HOST=$(hostname) || exit 1
TMP_DIR=''

usage() {
    cat <&2
    exit 1
}

cleanup() {
    if [[ -n $TMP_DIR && -d $TMP_DIR ]]; then
        rm -rf -- "$TMP_DIR"
    fi
}
trap cleanup EXIT
trap 'exit 1' HUP INT TERM

while (( $# > 0 )); do
    case $1 in
        -d|--database)
            (( $# >= 2 )) || fail "Missing argument for $1"
            DB=$2
            shift 2
            ;;
        -o|--output)
            (( $# >= 2 )) || fail "Missing argument for $1"
            OUT=$2
            shift 2
            ;;
        --files)
            FILES_ONLY=1
            shift
            ;;
        --rpm)
            RPM_MODE=1
            FILES_ONLY=1
            shift
            ;;
        --sha-csv|--csv)
            SHA_CSV_MODE=1
            RPM_MODE=1
            FILES_ONLY=1
            shift
            ;;
        -h|--help)
            usage
            exit 0
            ;;
        --)
            shift
            (( $# == 0 )) || fail "Unexpected positional arguments"
            ;;
        *)
            fail "Unknown argument: $1 (use --help)"
            ;;
    esac
 done

if [[ -z $OUT ]]; then
    if (( FILES_ONLY )); then
        OUT="$HOST.aide_db_regular_files.txt"
    else
        OUT="$HOST.aide_db_files.txt"
    fi
fi

[[ -f $DB && -r $DB ]] || fail "Database is missing or unreadable: $DB"
[[ -n $OUT && $OUT != */ ]] || fail "Invalid output filename"
DB_REAL=$(readlink -f -- "$DB") || fail "Cannot resolve database path"
OUT_DIR=$(dirname -- "$OUT")
[[ -d $OUT_DIR && -w $OUT_DIR ]] || fail "Output directory is not writable: $OUT_DIR"

OUTPUTS=("$OUT")
if (( RPM_MODE )); then
    command -v rpm >/dev/null 2>&1 || fail "The rpm command is required for --rpm"
    RPM_OWNED="$OUT_DIR/$HOST.aide_rpm_owned.txt"
    RPM_UNOWNED="$OUT_DIR/$HOST.aide_rpm_unowned.txt"
    RPM_PACKAGES="$OUT_DIR/$HOST.aide_rpm_packages.txt"
    OUTPUTS+=("$RPM_OWNED" "$RPM_UNOWNED" "$RPM_PACKAGES")
    if (( SHA_CSV_MODE )); then
        command -v python3 >/dev/null 2>&1 && PYTHON=python3
        if [[ -z ${PYTHON:-} && -x /usr/libexec/platform-python ]]; then
            PYTHON=/usr/libexec/platform-python
        fi
        [[ -n ${PYTHON:-} ]] || fail "Python 3 is required for --sha-csv"
        SHA_CSV="$OUT_DIR/$HOST.aide_sha_comparison.csv"
        OUTPUTS+=("$SHA_CSV")
    fi
fi

# Reject dangerous output collisions, including symlinks and hardlinks.
for (( i = 0; i < ${#OUTPUTS[@]}; i++ )); do
    target=${OUTPUTS[i]}
    [[ -n $target && $target != */ ]] || fail "Invalid output filename: $target"
    [[ ! -L $target ]] || fail "Refusing output symlink: $target"
    target_real=$(readlink -m -- "$target") || fail "Cannot resolve output path: $target"
    [[ $target_real != "$DB_REAL" ]] || fail "Output would overwrite the database: $target"
    [[ ! -e $target || ! $target -ef $DB ]] || fail "Output is a hardlink to the database: $target"
    for (( j = 0; j < i; j++ )); do
        previous=$(readlink -m -- "${OUTPUTS[j]}") || fail "Cannot resolve output path"
        [[ $target_real != "$previous" ]] || fail "Output filename collision: $target"
        [[ ! -e $target || ! -e ${OUTPUTS[j]} || ! $target -ef ${OUTPUTS[j]} ]] || fail "Output hardlink collision: $target"
    done
 done

if [[ $DB == *.gz ]]; then
    # Validate the entire gzip stream before processing it.
    gzip -t -- "$DB" || fail "Gzip database is damaged or incomplete: $DB"
    READER=(gzip -cd -- "$DB")
else
    READER=(cat -- "$DB")
fi

umask 077
TMP_DIR=$(mktemp -d "${OUT_DIR%/}/.aide-db-files.XXXXXXXX") || fail "Cannot create temporary directory"

# The @@db_spec header defines the positions of the name and perm columns.
# A regular file has S_IFREG (0100000) set in the octal Unix mode.
# Decode percent-encoded paths but retain encoded control bytes so one
# registered path occupies exactly one output line.
"${READER[@]}" | awk -v files_only="$FILES_ONLY" '
function hexval(c, p) {
    p = index("0123456789ABCDEF", toupper(c))
    return p ? p - 1 : -1
}
function is_regular_mode(s,    i, n, d, kind) {
    if (s !~ /^[0-7]+$/)
        return -1
    n = 0
    for (i = 1; i <= length(s); i++) {
        d = substr(s, i, 1) + 0
        n = n * 8 + d
    }
    kind = int(n / 4096) % 16
    if (kind == 8)
        return 1
    if (kind == 1 || kind == 2 || kind == 4 || kind == 6 || kind == 10 || kind == 12)
        return 0
    return -1
}
function decode_path(s,    out, i, a, b, n, ch) {
    out = ""
    for (i = 1; i <= length(s); i++) {
        ch = substr(s, i, 1)
        if (ch == "%" && i + 2 <= length(s)) {
            a = hexval(substr(s, i + 1, 1))
            b = hexval(substr(s, i + 2, 1))
            if (a >= 0 && b >= 0) {
                n = a * 16 + b
                if (n < 32 || n == 127)
                    out = out substr(s, i, 3)
                else
                    out = out sprintf("%c", n)
                i += 2
                continue
            }
        }
        out = out ch
    }
    return out
}
/^@@begin_db([[:space:]]|$)/ { started = 1; next }
/^@@db_spec[[:space:]]/ {
    if (!started || spec_seen) { bad = 1; next }
    spec_seen = 1
    for (i = 2; i <= NF; i++)
        if ($i == "name") { namecol = i - 1; break }
    for (i = 2; i <= NF; i++)
        if ($i == "perm") { permcol = i - 1; break }
    if (!namecol || (files_only && !permcol)) bad = 1
    next
}
/^@@end_db([[:space:]]|$)/ { ended = 1; next }
/^@@/ || /^#/ || /^[[:space:]]*$/ { next }
{
    if (!spec_seen || ended || !namecol || NF < namecol || $namecol !~ /^\//) {
        bad = 1
        next
    }
    count++
    if (files_only) {
        if (NF < permcol || (mode = is_regular_mode($permcol)) < 0) {
            bad = 1
            next
        }
        if (mode == 0)
            next
    }
    print decode_path($namecol)
}
END {
    if (!started || !spec_seen || !namecol || (files_only && !permcol) || !count || bad) {
        if (files_only && !permcol)
            print "AIDE database has no perm column; cannot classify file types" > "/dev/stderr"
        else
            print "Invalid AIDE database structure, file type, or no registered paths found" > "/dev/stderr"
        exit 1
    }
}
' > "$TMP_DIR/paths"
status=("${PIPESTATUS[@]}")
if (( status[0] != 0 || status[1] != 0 )); then
    fail "Unable to read or parse AIDE database"
fi

sort -u -o "$TMP_DIR/paths" "$TMP_DIR/paths" || fail "Failed to sort paths"
COUNT=$(wc -l < "$TMP_DIR/paths") || fail "Failed to count paths"

if (( RPM_MODE )); then
    # A single RPM query returns every installed file and its owning NEVRA.
    # The leading = pins scalar package tags inside the FILENAMES iterator.
    # This avoids ARG_MAX problems and thousands of rpm -qf subprocesses.
    if (( SHA_CSV_MODE )); then
        RPM_FORMAT='[%{FILENAMES}\t%{=NAME}-%{=VERSION}-%{=RELEASE}.%{=ARCH}\t%{FILEDIGESTS}\t%{=FILEDIGESTALGO}\n]'
    else
        RPM_FORMAT='[%{FILENAMES}\t%{=NAME}-%{=VERSION}-%{=RELEASE}.%{=ARCH}\n]'
    fi
    rpm -qa --qf "$RPM_FORMAT" > "$TMP_DIR/rpm-map" 2> "$TMP_DIR/rpm.err"
    if (( $? != 0 )); then
        cat -- "$TMP_DIR/rpm.err" >&2
        fail "Cannot query installed RPM package file lists"
    fi
    [[ -s $TMP_DIR/rpm-map ]] || fail "RPM database returned no file entries"

    : > "$TMP_DIR/owned"
    : > "$TMP_DIR/unowned"
    : > "$TMP_DIR/packages"

    # The RPM digest fields are appended after the package name in CSV mode.
    # Keep paths as the first AWK input, then match exact RPM pathnames.
    awk -v owned="$TMP_DIR/owned" \
        -v unowned="$TMP_DIR/unowned" \
        -v packages="$TMP_DIR/packages" \
        -v sha_mode="$SHA_CSV_MODE" '
        NR == FNR { aide[$0] = 1; next }
        {
            if (sha_mode) {
                # Strip the trailing digest and algorithm columns first.
                sub(/\t[^\t]*\t[^\t]*$/, "", $0)
            }
            sep = match($0, /\t[^\t]*$/)
            if (!sep) { invalid = 1; next }
            path = substr($0, 1, sep - 1)
            package = substr($0, sep + 1)
            if (package == "" || path !~ /^\//) { invalid = 1; next }
            if (path in aide) {
                found[path] = 1
                matching_packages[package] = 1
            }
        }
        END {
            if (invalid) {
                print "Invalid RPM file mapping returned by rpm" > "/dev/stderr"
                exit 1
            }
            for (path in aide) {
                if (path in found) print path > owned
                else print path > unowned
            }
            for (package in matching_packages) print package > packages
        }
    ' "$TMP_DIR/paths" "$TMP_DIR/rpm-map" || fail "Cannot correlate AIDE entries with RPM packages"

    for name in owned unowned packages; do
        sort -u -o "$TMP_DIR/$name" "$TMP_DIR/$name" || fail "Cannot sort RPM $name report"
    done
    OWNED_COUNT=$(wc -l < "$TMP_DIR/owned") || fail "Cannot count RPM owned paths"
    UNOWNED_COUNT=$(wc -l < "$TMP_DIR/unowned") || fail "Cannot count RPM unowned paths"
    PACKAGE_COUNT=$(wc -l < "$TMP_DIR/packages") || fail "Cannot count RPM packages"
    (( OWNED_COUNT + UNOWNED_COUNT == COUNT )) || fail "RPM correlation counts do not match the AIDE path list"
fi

if (( SHA_CSV_MODE )); then
    # Use Python's CSV writer for correct quoting and its hash functions for
    # a single streaming pass through each currently existing regular file.
    cat > "$TMP_DIR/sha_report.py" <<'PY_SHA_REPORT'
#!/usr/bin/env python3
"""Build a read-only AIDE/RPM/current-file digest comparison CSV."""
import base64
import collections
import csv
import gzip
import hashlib
import os
import re
import stat
import sys
from urllib.parse import unquote


def db_lines(database):
    opener = gzip.open if database.endswith('.gz') else open
    with opener(database, 'rt', encoding='utf-8', errors='surrogateescape') as handle:
        for line in handle:
            yield line.rstrip('\r\n')


def decode_path(value):
    # Preserve encoded control bytes to match the existing text reports.
    value = re.sub(r'%([0-9a-fA-F]{2})',
                   lambda m: '%25' + m.group(1)
                   if int(m.group(1), 16) < 32 or int(m.group(1), 16) == 127
                   else m.group(0), value)
    return unquote(value, encoding='utf-8', errors='surrogateescape')


def decode_aide_sha256(value):
    if not value or value in ('0', '(none)', '-'):
        return '', False
    if re.fullmatch(r'[0-9A-Fa-f]{64}', value):
        return value.lower(), False
    try:
        digest = base64.b64decode(value, validate=True)
        if len(digest) == 32:
            return digest.hex(), False
    except (ValueError, base64.binascii.Error):
        pass
    return '', True


def read_aide_digests(database, wanted):
    digests = {}
    started = False
    spec = None
    count = 0
    for line in db_lines(database):
        if line.startswith('@@begin_db'):
            started = True
            continue
        if line.startswith('@@db_spec'):
            if not started or spec is not None:
                raise ValueError('Invalid or duplicate AIDE @@db_spec')
            spec = line.split()[1:]
            if 'name' not in spec:
                raise ValueError('AIDE @@db_spec lacks name')
            continue
        if line.startswith('@@end_db'):
            break
        if not line or line.startswith('#') or line.startswith('@@'):
            continue
        if spec is None:
            raise ValueError('AIDE entry found before @@db_spec')
        fields = line.split()
        if len(fields) < len(spec):
            raise ValueError('Short AIDE database entry')
        path = decode_path(fields[spec.index('name')])
        count += 1
        if path in wanted:
            raw = fields[spec.index('sha256')] if 'sha256' in spec else ''
            if path in digests:
                raise ValueError('Duplicate regular file in AIDE database: ' + path)
            digests[path] = decode_aide_sha256(raw)
    if not started or spec is None or not count:
        raise ValueError('Invalid or empty AIDE database')
    if len(digests) != len(wanted):
        missing = wanted - digests.keys()
        raise ValueError('AIDE path/digest mismatch (example: %s)' % next(iter(missing)))
    return digests


def normalize_rpm_algorithm(value):
    names = {
        '0': 'md5', '1': 'md5', '2': 'sha1', '8': 'sha256',
        '9': 'sha384', '10': 'sha512', '11': 'sha224',
        '(none)': 'md5', '': 'md5',
    }
    return names.get(value.strip(), 'unknown:' + value.strip())


def read_rpm_map(filename, wanted):
    owners = collections.defaultdict(list)
    with open(filename, 'r', encoding='utf-8', errors='surrogateescape') as handle:
        for line in handle:
            parts = line.rstrip('\r\n').rsplit('\t', 3)
            if len(parts) != 4:
                raise ValueError('Unexpected RPM file digest output format')
            path, package, digest, algo_id = parts
            if path not in wanted:
                continue
            algorithm = normalize_rpm_algorithm(algo_id)
            digest = digest.strip().lower()
            if digest in ('(none)', '(not a number)', '(null)'):
                digest = ''
            owners[path].append((package, algorithm, digest))
    return owners


def digest_of_current_file(path, rpm_algorithm):
    flags = os.O_RDONLY
    flags |= getattr(os, 'O_CLOEXEC', 0)
    flags |= getattr(os, 'O_NOFOLLOW', 0)
    flags |= getattr(os, 'O_NONBLOCK', 0)
    try:
        fd = os.open(path, flags)
    except FileNotFoundError:
        return '', '', 'MISSING'
    except OSError as exc:
        if exc.errno in (getattr(__import__('errno'), 'ELOOP'),):
            return '', '', 'NOT_REGULAR'
        return '', '', 'UNREADABLE'

    with os.fdopen(fd, 'rb') as handle:
        try:
            before = os.fstat(handle.fileno())
            if not stat.S_ISREG(before.st_mode):
                return '', '', 'NOT_REGULAR'
            sha = hashlib.sha256()
            second = None
            if rpm_algorithm and rpm_algorithm != 'sha256':
                try:
                    second = hashlib.new(rpm_algorithm)
                except (ValueError, TypeError):
                    pass
            while True:
                block = handle.read(1024 * 1024)
                if not block:
                    break
                sha.update(block)
                if second is not None:
                    second.update(block)
            after = os.fstat(handle.fileno())
        except OSError:
            return '', '', 'UNREADABLE'
    try:
        final = os.stat(path, follow_symlinks=False)
    except OSError:
        return '', '', 'CHANGED_DURING_READ'
    identity = lambda st: (st.st_dev, st.st_ino, st.st_size, st.st_mtime_ns, st.st_ctime_ns)
    if identity(before) != identity(after) or identity(after) != identity(final):
        return '', '', 'CHANGED_DURING_READ'
    disk_sha = sha.hexdigest()
    rpm_digest = disk_sha if rpm_algorithm == 'sha256' else (second.hexdigest() if second is not None else '')
    return disk_sha, rpm_digest, ''


def comparison(expected, current):
    if not expected or not current:
        return 'UNAVAILABLE'
    return 'MATCH' if expected == current else 'DIFFERENT'


def main():
    database, paths_file, rpm_map_file, csv_file, summary_file = sys.argv[1:]
    with open(paths_file, 'r', encoding='utf-8', errors='surrogateescape') as handle:
        paths = [line.rstrip('\n') for line in handle]
    wanted = set(paths)
    if len(wanted) != len(paths) or not paths:
        raise ValueError('Empty or duplicate AIDE path list')
    aide = read_aide_digests(database, wanted)
    rpm = read_rpm_map(rpm_map_file, wanted)
    counts = collections.Counter()
    columns = [
        'path', 'rpm_package', 'aide_sha256', 'rpm_sha256', 'current_sha256',
        'rpm_digest_algorithm', 'rpm_digest', 'current_rpm_digest',
        'aide_vs_current', 'rpm_vs_current', 'aide_vs_rpm', 'status'
    ]
    with open(csv_file, 'w', newline='', encoding='utf-8', errors='backslashreplace') as handle:
        writer = csv.writer(handle)
        writer.writerow(columns)
        for path in paths:
            aide_sha, aide_bad = aide[path]
            records = rpm.get(path, [])
            packages = sorted({r[0] for r in records})
            digests = {(r[1], r[2]) for r in records if r[2]}
            conflict = len(digests) > 1
            algo, rpm_digest = next(iter(digests)) if len(digests) == 1 else ('', '')
            if not digests and records:
                algo = records[0][1]
            disk_sha, disk_rpm_digest, disk_error = digest_of_current_file(path, algo)
            rpm_sha = rpm_digest if algo == 'sha256' else ''
            aide_now = comparison(aide_sha, disk_sha)
            rpm_now = comparison(rpm_digest, disk_rpm_digest)
            aide_rpm = comparison(aide_sha, rpm_sha)
            if not records:
                rpm_now = 'NOT_OWNED'
                aide_rpm = 'NOT_OWNED'
            if conflict:
                rpm_now = 'AMBIGUOUS'
                aide_rpm = 'AMBIGUOUS'
            if rpm_digest and algo.startswith('unknown:'):
                rpm_now = 'UNSUPPORTED_ALGORITHM'
            if disk_error:
                status = disk_error
            elif aide_bad:
                status = 'INVALID_AIDE_SHA256'
            elif conflict:
                status = 'RPM_MULTIPLE_DIGESTS'
            elif not records:
                status = 'RPM_UNOWNED'
            elif not aide_sha:
                status = 'NO_AIDE_SHA256'
            elif not rpm_digest:
                status = 'NO_RPM_DIGEST'
            elif rpm_now == 'UNSUPPORTED_ALGORITHM':
                status = 'UNSUPPORTED_RPM_DIGEST'
            elif aide_now == 'MATCH' and rpm_now == 'MATCH':
                status = 'ALL_MATCH'
            elif aide_now == 'MATCH' and rpm_now == 'DIFFERENT':
                status = 'RPM_DIFFERS'
            elif aide_now == 'DIFFERENT' and rpm_now == 'MATCH':
                status = 'AIDE_DIFFERS'
            elif aide_now == 'DIFFERENT' and rpm_now == 'DIFFERENT':
                status = 'BOTH_DIFFER'
            else:
                status = 'INDETERMINATE'
            counts[status] += 1
            writer.writerow([
                path, ';'.join(packages), aide_sha, rpm_sha, disk_sha,
                algo, rpm_digest, disk_rpm_digest,
                aide_now, rpm_now, aide_rpm, status
            ])
    with open(summary_file, 'w', encoding='ascii') as handle:
        handle.write('SHA comparison entries: %d\n' % len(paths))
        for status, count in sorted(counts.items()):
            handle.write('  %-25s %d\n' % (status + ':', count))


if __name__ == '__main__':
    try:
        main()
    except (OSError, ValueError, UnicodeError) as exc:
        sys.exit('SHA report: ' + str(exc))
PY_SHA_REPORT
    "$PYTHON" "$TMP_DIR/sha_report.py" "$DB" "$TMP_DIR/paths" \
        "$TMP_DIR/rpm-map" "$TMP_DIR/sha.csv" "$TMP_DIR/sha_summary" \
        || fail "Cannot build SHA comparison report"
fi

# Publish completed reports only after all database reads and checks succeed.
if (( SHA_CSV_MODE )); then
    mv -f -- "$TMP_DIR/sha.csv" "$SHA_CSV" || fail "Cannot save report: $SHA_CSV"
fi
if (( RPM_MODE )); then
    mv -f -- "$TMP_DIR/owned" "$RPM_OWNED" || fail "Cannot save report: $RPM_OWNED"
    mv -f -- "$TMP_DIR/unowned" "$RPM_UNOWNED" || fail "Cannot save report: $RPM_UNOWNED"
    mv -f -- "$TMP_DIR/packages" "$RPM_PACKAGES" || fail "Cannot save report: $RPM_PACKAGES"
fi
mv -f -- "$TMP_DIR/paths" "$OUT" || fail "Cannot save report: $OUT"

printf 'Database: %s\nOutput: %s\n' "$DB" "$OUT"
if (( FILES_ONLY )); then
    printf 'Registered regular files: %s\n' "$COUNT"
else
    printf 'Registered paths: %s\n' "$COUNT"
fi
if (( RPM_MODE )); then
    printf 'RPM-owned files: %s (%s)\n' "$OWNED_COUNT" "$RPM_OWNED"
    printf 'RPM-unowned files: %s (%s)\n' "$UNOWNED_COUNT" "$RPM_UNOWNED"
    printf 'Unique RPM packages: %s (%s)\n' "$PACKAGE_COUNT" "$RPM_PACKAGES"
fi
if (( SHA_CSV_MODE )); then
    printf 'SHA comparison CSV: %s\n' "$SHA_CSV"
    cat -- "$TMP_DIR/sha_summary"
fi