#!/bin/bash

# Default values
INPUT_FILE=""
FULL_OUTPUT=0

show_help() {
    echo "Usage: $0 [OPTIONS]"
    echo ""
    echo "Options:"
    echo "  -h, --help          Show this help message"
    echo "  -i, --input <file>  Specify the input file containing the message list"
    echo "  -f, --full          Output all test results (Default: only output discrepancies/errors)"
    echo ""
    exit 0
}

# Parse parameters
while [[ $# -gt 0 ]]; do
    case "$1" in
        -h|--help)
            show_help
            ;;
        -i|--input)
            INPUT_FILE="$2"
            shift 2
            ;;
        -f|--full)
            FULL_OUTPUT=1
            shift
            ;;
        *)
            echo "Unknown option: $1"
            show_help
            ;;
    esac
done

# Validate input
if [ -z "$INPUT_FILE" ]; then
    echo "Error: Input file must be specified with -i or --input."
    exit 1
fi

if [ ! -f "$INPUT_FILE" ]; then
    echo "Error: Input file '$INPUT_FILE' does not exist."
    exit 1
fi

# Counters for summary
TOTAL_CHECKED=0
CORRECT_REPORTS=0
FALSE_REPORTS=0

# ANSI Escape Codes for Colors
GREEN="\033[1;32m"
RED="\033[1;31m"
RESET="\033[0m"

while read -r line; do
    [[ -z "$line" ]] && continue

    # Regex matching G.W. Haywood layout string exactly
    if [[ $line =~ Found\ \[([a-f0-9]{32})\]\ in\ host\ \[(.*?)\]\ backup\ number\ \[([0-9]+)\]\ share\ \[(.*?)\]\ file\ \[(.*?)\] ]]; then
        ((TOTAL_CHECKED++))
        
        ged_hash="${BASH_REMATCH[1]}"
        host="${BASH_REMATCH[2]}"
        bnum="${BASH_REMATCH[3]}"
        share="${BASH_REMATCH[4]}"
        rel_path="${BASH_REMATCH[5]}"

        dir_part=$(dirname "$rel_path")
        file_part=$(basename "$rel_path")
        clean_file_part=$(echo "$file_part" | tr -d '@')

        if [ "$dir_part" = "." ]; then dir_part=""; fi

        # Reconstruct standard BackupPC v4 directory layouts using nested f-prefixes
        if [ -n "$dir_part" ]; then
            f_dir_part=$(echo "$dir_part" | sed -E 's|([^/]+)|f\1|g')
            f_full_dir="/var/lib/backuppc/pc/$host/$bnum/f$share/$f_dir_part"
        else
            f_full_dir="/var/lib/backuppc/pc/$host/$bnum/f$share"
        fi

        IS_CORRECT=0
        MESSAGE=""

        if [ -d "$f_full_dir" ]; then
            attrib_content=$(sudo -u backuppc /usr/share/backuppc/bin/BackupPC_attribPrint "$f_full_dir"/attrib_* 2>/dev/null | tr -d '\0')
            real_file_name=$(echo "$attrib_content" | grep -oP "'\K$clean_file_part[^']*(?=' =>)" | head -n 1)

            if [ -n "$real_file_name" ]; then
                file_block=$(echo "$attrib_content" | grep -A11 -B1 "'$real_file_name' =>")
                real_hash=$(echo "$file_block" | grep -oP "'digest' => '\K[a-f0-9]*")

                if [ -n "$real_hash" ]; then
 
                    b1_val=$(( (16#${real_hash:0:2}) & 0xfe ))
                    b2_val=$(( (16#${real_hash:2:2}) & 0xfe ))
                    b1=$(printf "%02x" "$b1_val")
                    b2=$(printf "%02x" "$b2_val")
                    pool_file="/var/lib/backuppc/pool/$b1/$b2/$real_hash"

                    if [ -f "$pool_file" ]; then
                        pool_size=$(stat -c %s "$pool_file")
                        ls_pool_output=$(ls -l "$pool_file" 2>/dev/null)
                        if [ "$pool_size" -eq 0 ]; then
                            # Confirmation: Verified as 0-byte structural error
                            IS_CORRECT=1
                            MESSAGE="${GREEN}SUCCESS: POOL FILE CORRUPT (0 BYTES) -> $pool_file (Attrib Hash: $real_hash)${RESET}\n   Physisches Pool-File:\n   -> $ls_pool_output"
                        else
                            # Discrepancy: File exists healthy in pool, but ged reported error
                            IS_CORRECT=0
                            MESSAGE="${RED}FAILURE: POOL FILE OK ($pool_size Bytes) -> $pool_file (Attrib Hash: $real_hash)${RESET}\n   Physisches Pool-File:\n   -> $ls_pool_output"
                        fi
                    else
                        # Confirmation: Verified as physically missing pool link
                        IS_CORRECT=1
                        MESSAGE="${GREEN}SUCCESS: POOL FILE MISSING COMPLETELY -> $pool_file (Attrib Hash: $real_hash)${RESET}"
                    fi
                else
                    # Discrepancy: E.g., Directory or empty reference that never holds pool data
                    IS_CORRECT=0
                    real_dir_path="${f_full_dir}/f${real_file_name}"
                    ls_output=$(ls -ld "$real_dir_path" 2>/dev/null)
                    MESSAGE="${RED}FAILURE: ATTRIB HAS NO DIGEST (Directory/Index empty reference)${RESET}\n   Physisches Verzeichnis im Backup:\n   -> $ls_output"
                fi
            else
                # Discrepancy: File truncated or vanished from real directory tree
                IS_CORRECT=0
                MESSAGE="${RED}FAILURE: ATTRIB ENTRY NOT FOUND IN FILE TREE${RESET}"
            fi
        else
            # Discrepancy: Directory path itself completely invalid/phantom
            IS_CORRECT=0
            MESSAGE="${RED}FAILURE: DIRECTORY PATH DOES NOT EXIST ON DISK${RESET}"
        fi

        # Stat tracking update
        if [ "$IS_CORRECT" -eq 1 ]; then
            ((CORRECT_REPORTS++))
            # Output only if full mode is requested
            if [ "$FULL_OUTPUT" -eq 1 ]; then
                echo "--------------------------------------------------------------------------------"
                echo "$line"
                echo -e "$MESSAGE"
            fi
        else
            ((FALSE_REPORTS++))
            # Discrepancies/Errors are always printed
            echo "--------------------------------------------------------------------------------"
            echo "$line"
            echo -e "$MESSAGE"
        fi
    fi
done < "$INPUT_FILE"

# Print Final Statistics Summary
echo "================================================================================"
echo "   FINAL FORENSIC VALIDATION SUMMARY"
echo "================================================================================"
echo "   Total unique lines parsed    : $TOTAL_CHECKED"
echo -e "   Correct reports (Verified)   : ${GREEN}$CORRECT_REPORTS${RESET}"
echo -e "   False reports (Mismatches)   : ${RED}$FALSE_REPORTS${RESET}"
echo "================================================================================"
