#!/bin/bash

# Script to synchronize MITRE CVE data with this repository
# Purpose: Clones or updates CVE data from the official MITRE CVE repository into the local cve-data directory
# Usage: Run ./update-cve-data.sh from the repository root
# Requirements: Git must be installed and configured

# Exit on any error
set -e

# Directory where CVE data will be stored
CVE_DIR="cve-data"

# Official MITRE CVE repository URL
CVE_REPO="https://github.com/CVEProject/cvelistV5.git"

# Check if Git is installed
if ! command -v git &> /dev/null; then
    echo "Error: Git is not installed. Please install Git and try again."
    exit 1
fi

# Check if the cve-data directory exists
if [ -d "$CVE_DIR" ]; then
    echo "Updating existing CVE data in $CVE_DIR..."
    cd "$CVE_DIR"
    git pull origin main || { echo "Error: Failed to update CVE data."; exit 1; }
    cd ..
else
    echo "Cloning CVE data from $CVE_REPO into $CVE_DIR..."
    git clone "$CVE_REPO" "$CVE_DIR" || { echo "Error: Failed to clone CVE data."; exit 1; }
fi

# Record the last update time
echo "Last updated: $(date)" > "$CVE_DIR/last-updated.txt"

# Add and commit the changes to your repository
git add "$CVE_DIR"
git commit -m "Update CVE data from CVEProject/cvelistV5 - $(date)" || echo "No changes to commit."
echo "CVE data updated successfully. Run 'git push' to upload the changes to your repository."