#!/bin/bash
# cve-scan-z.sh - Dynamic CVE and update scanner for AM·OS z-series
set -uo pipefail

SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd -P)"
REPO="$(cd -- "$SCRIPT_DIR/.." && pwd -P)"
Z_TREE="$REPO/amos64/z"
REPOLOGY_API="https://repology.org/api/v1/project"
OSV_API="https://api.osv.dev/v1/query"
DEBUG="${DEBUG:-0}"

declare -A CURRENT_VERSIONS
declare -A LATEST_VERSIONS
declare -A REPO_FOUND_MAP

echo "1. Collecting packages and querying Repology for updates..."
echo "-------------------------------------------------------------------------"

for txz in "$Z_TREE"/*.txz; do
    [ -f "$txz" ] || continue
    pkg_filename=$(basename "$txz")
    base="${pkg_filename%.txz}"
    name_ver="${base%-*-*}"
    pkg_name="${name_ver%-*}"
    pkg_version="${name_ver##*-}"
    CURRENT_VERSIONS["$pkg_name"]="$pkg_version"
done

for pkg_name in "${!CURRENT_VERSIONS[@]}"; do
    pkg_version="${CURRENT_VERSIONS[$pkg_name]}"
    res=$(curl -s -H "User-Agent: AMOS-CVE-Scanner/1.0" "$REPOLOGY_API/$pkg_name" 2>/dev/null)
    
    if echo "$res" | jq -e 'type == "array" and length > 0' >/dev/null 2>&1; then
        REPO_FOUND_MAP["$pkg_name"]=1
        latest_version=$(echo "$res" | jq -r '.[] | select(.status == "newest") | .version' 2>/dev/null | head -n 1)
        
        if [ -n "$latest_version" ] && [ "$latest_version" != "$pkg_version" ]; then
            newer_check=$(printf '%s\n%s\n' "$latest_version" "$pkg_version" | sort -V | tail -n1)
            if [ "$newer_check" = "$latest_version" ]; then
                LATEST_VERSIONS["$pkg_name"]="$latest_version"
            fi
        fi
    else
        REPO_FOUND_MAP["$pkg_name"]=0
    fi
    sleep 1
done

echo "2. Generating Report..."
echo "-------------------------------------------------------------------------"

for pkg_name in $(printf '%s\n' "${!CURRENT_VERSIONS[@]}" | sort); do
    pkg_version="${CURRENT_VERSIONS[$pkg_name]}"
    latest_version="${LATEST_VERSIONS[$pkg_name]:-}"
    repo_found="${REPO_FOUND_MAP[$pkg_name]:-0}"
    
    echo "Checking $pkg_name ($pkg_version)..."
    
    if [ "$DEBUG" -eq 1 ]; then
        echo "  [DEBUG] Repology array length: $([ "$repo_found" -eq 1 ] && echo ">0" || echo "0")"
    fi

    if [ "$repo_found" -eq 1 ]; then
        if [ -n "$latest_version" ]; then
            echo "  ℹ️  Latest upstream version is $latest_version (You have: $pkg_version)"
        else
            echo "  ℹ️  You are on the latest upstream version tracked by Repology."
        fi
    else
        echo "  ℹ️  Package not found in Repology."
    fi

    # Collect from ALL ecosystems instead of breaking early
    RAW_CVES=()
    OSV_MATCHED=0
    
    for eco in "GITHUB" "PyPI" "npm" "Debian"; do
        payload="{\"package\": {\"name\": \"$pkg_name\", \"ecosystem\": \"$eco\"}}"
        res=$(curl -s -X POST "$OSV_API" -H 'Content-Type: application/json' -d "$payload" 2>/dev/null)
        
        if [ "$DEBUG" -eq 1 ]; then
            echo "  [DEBUG] Querying OSV: $payload"
            echo "$res" > "/tmp/osv_raw_${pkg_name}_${eco}.json"
            if echo "$res" | jq -e '.vulns' >/dev/null 2>&1; then
                echo "  [DEBUG] OSV returned vulnerabilities for $eco. Raw count: $(echo "$res" | jq '.vulns | length')"
            fi
        fi

        if echo "$res" | jq -e '.vulns' >/dev/null 2>&1; then
            OSV_MATCHED=1
            mapfile -t -O "${#RAW_CVES[@]}" RAW_CVES < <(echo "$res" | jq -r '
              .vulns[]? |
              (.upstream[0] // .id) as $cve |
              [.affected[]?.ranges[]?.events[]?.fixed?] | map(select(. != null)) | first as $fixed |
              if $fixed then
                ($fixed | sub("^[0-9]+:"; "") | sub("-.*$"; "")) as $base_fixed |
                "\($cve)|\($base_fixed)"
              else
                "\($cve)|UNPATCHED"
              end
            ' 2>/dev/null)
        fi
    done

    if [ "$DEBUG" -eq 1 ] && [ ${#RAW_CVES[@]} -gt 0 ]; then
        echo "  [DEBUG] Raw CVEs extracted across all ecosystems (before filtering):"
        printf "           %s\n" "${RAW_CVES[@]}"
    fi

    ACTIVE_CVES=()
    if [ ${#RAW_CVES[@]} -gt 0 ]; then
        # Deduplicate before processing
        mapfile -t UNIQUE_CVES < <(printf "%s\n" "${RAW_CVES[@]}" | sort -u)
        
        for entry in "${UNIQUE_CVES[@]}"; do
            [ -z "$entry" ] && continue
            cve_id="${entry%|*}"
            fixed_ver="${entry#*|}"
            cve_year=$(echo "$cve_id" | grep -oE '[0-9]{4}' | head -1)
            
            if [ "$fixed_ver" = "UNPATCHED" ]; then
                # Rule 3: Flag Ancient CVEs
                if [ -n "$cve_year" ] && [ "$cve_year" -lt 2015 ]; then
                    ACTIVE_CVES+=("$cve_id (Ancient/Unpatched)")
                else
                    ACTIVE_CVES+=("$cve_id (No fix known)")
                fi
            else
                # Rule 2: Repology Sanity Check (Ignore fixes from other projects, e.g., BIND in Unbound)
                if [ -n "$latest_version" ]; then
                    higher_check=$(printf '%s\n%s\n' "$fixed_ver" "$latest_version" | sort -V | tail -n1)
                    if [ "$higher_check" = "$fixed_ver" ] && [ "$fixed_ver" != "$latest_version" ]; then
                        if [ "$DEBUG" -eq 1 ]; then echo "  [DEBUG] Ignoring false positive $cve_id (Fix $fixed_ver > Latest $latest_version)"; fi
                        continue
                    fi
                fi

                newer=$(printf '%s\n%s\n' "$fixed_ver" "$pkg_version" | sort -V | tail -n1)
                if [ "$newer" != "$pkg_version" ]; then
                    ACTIVE_CVES+=("$cve_id (Fixed in $fixed_ver)")
                fi
            fi
        done
    fi

    if [ ${#ACTIVE_CVES[@]} -gt 0 ]; then
        mapfile -t ACTIVE_CVES < <(printf '%s\n' "${ACTIVE_CVES[@]}" | sort -u)
        echo "  ⚠️  CURRENT version has ${#ACTIVE_CVES[@]} active CVE(s)."
        printf "     - %s\n" "${ACTIVE_CVES[@]}"
    else
        if [ "$repo_found" -eq 0 ] && [ "$OSV_MATCHED" -eq 0 ]; then
            echo "  ℹ️  No active CVEs found (Package likely not tracked by OSV)."
        elif [ -n "$latest_version" ]; then
            # NEW: Warn if you are behind but OSV found nothing
            echo "  ⚠️  OSV reports no active CVEs, BUT you are behind upstream ($latest_version)."
            echo "      (OSV may not track this package. Check the upstream changelog for new CVEs)."
        else
            echo "  ✅ No active CVEs found for this version."
        fi
    fi
    echo ""
    sleep 1
done