#!/bin/bash

# Ensure script is run as root
if [ "$EUID" -ne 0 ]; then
    echo "[-] Error: This script must be run as root." >&2
    exit 1
fi

# Check if directory argument is provided
if [ -z "$1" ]; then
    echo "[-] Usage: $0 <target_directory>" >&2
    exit 1
fi

TARGET_DIR="$1"

if [ ! -d "$TARGET_DIR" ]; then
    echo "[-] Error: '$TARGET_DIR' is not a valid directory." >&2
    exit 1
fi

# Interactive password prompt (hidden input)
echo -n "Enter archive password for full decryption test (or press Enter to skip): "
read -s PASSWORD
echo "" # Print a newline after hidden input

echo "[*] Scanning directory recursively: $TARGET_DIR"
if [ -n "$PASSWORD" ]; then
    echo "[*] Password provided: Archive full decryption & integrity test enabled."
else
    echo "[*] Password skipped: Running signature, header encryption check, and SHA512 verification."
fi
echo "--------------------------------------------------"

ERROR_COUNT=0
FILE_COUNT=0

while IFS= read -r -d '' file; do
    FILE_COUNT=$((FILE_COUNT + 1))
    filename=$(basename "$file")
    failed=0

    echo "[*] Checking: $file"

    # 1. Check if file ends in .7z or .sha512
    if [[ "$filename" != *.7z && "$filename" != *.sha512 ]]; then
        echo "    [X] Failed extension check: does not end in .7z or .sha512"
        failed=1
    else
        echo "    [+] Extension check passed ($filename)"
    fi

    # 2. Check and enforce ownership (root:root)
    owner=$(stat -c '%U:%G' "$file")
    if [ "$owner" != "root:root" ]; then
        echo "    [!] Incorrect ownership ($owner). Fixing to root:root..."
        chown root:root "$file"
        if [ $? -ne 0 ]; then
            echo "    [X] Failed to change ownership to root:root."
            failed=1
        else
            echo "    [+] Ownership corrected to root:root."
        fi
    else
        echo "    [+] Ownership check passed (root:root)."
    fi

    # 3. Check and enforce permissions (600)
    perms=$(stat -c '%a' "$file")
    if [ "$perms" != "600" ]; then
        echo "    [!] Incorrect permissions ($perms). Fixing to 600..."
        chmod 600 "$file"
        if [ $? -ne 0 ]; then
            echo "    [X] Failed to change permissions to 600."
            failed=1
        else
            echo "    [+] Permissions corrected to 600."
        fi
    else
        echo "    [+] Permissions check passed (600)."
    fi

    # 4. If it is a .7z file, perform verification and SHA512 management
    if [[ "$filename" == *.7z ]]; then
        if [ -n "$PASSWORD" ]; then
            # Full decryption and integrity test using the provided password
            if ! 7z t -p"$PASSWORD" "$file" >/dev/null 2>&1; then
                echo "    [X] Failed integrity/decryption check: Incorrect password, corrupted archive, or invalid data."
                failed=1
            else
                echo "    [+] Archive successfully decrypted and integrity verified with password."
            fi
        else
            # Fallback mode: Signature check + Header encryption verification
            expected_header=$'\x37\x7a\xbc\xaf\x27\x1c'
            file_header=$(head -c 6 "$file")
            if [ "$file_header" != "$expected_header" ]; then
                echo "    [X] Failed format check: Not a valid 7-zip file signature."
                failed=1
            else
                echo "    [+] Valid 7-zip file signature confirmed."
                
                # Confirm header/filename encryption is active (-mhe=on)
                if 7z l "$file" </dev/null >/dev/null 2>&1; then
                    echo "    [X] Failed encryption check: Archive headers/filenames are NOT encrypted."
                    failed=1
                else
                    echo "    [+] Filename and header encryption confirmed (-mhe=on active)."
                fi
            fi
        fi

        # SHA512 check / generation
        sha_file="${file}.sha512"
        if [ ! -f "$sha_file" ]; then
            echo "    [!] Missing .sha512 file. Generating..."
            sha512sum "$file" > "$sha_file"
            chown root:root "$sha_file"
            chmod 600 "$sha_file"
            if [ $? -eq 0 ]; then
                echo "    [+] Generated and secured new SHA512 checksum file."
            else
                echo "    [X] Failed to generate or secure SHA512 checksum file."
                failed=1
            fi
        else
            echo "    [+] Found existing .sha512 file. Verifying..."
            file_dir=$(dirname "$file")
            base_sha=$(basename "$sha_file")
            
            if (cd "$file_dir" && sha512sum -c "$base_sha" >/dev/null 2>&1); then
                echo "    [+] SHA512 hash verification passed."
            else
                echo "    [X] FAILED: SHA512 hash verification failed!"
                failed=1
            fi
        fi
    fi

    if [ $failed -eq 1 ]; then
        echo "    [-] STATUS: FILE COMPLIANCE FAILED"
        ERROR_COUNT=$((ERROR_COUNT + 1))
    else
        echo "    [+] STATUS: OK"
    fi
    echo ""

done < <(find "$TARGET_DIR" -type f -print0)

echo "--------------------------------------------------"
echo "[*] Scan complete."
echo "    Total files checked: $FILE_COUNT"
echo "    Files with compliance failures: $ERROR_COUNT"

if [ $ERROR_COUNT -gt 0 ]; then
    exit 1
else
    exit 0
fi