#!/bin/bash

# BizMatch Vulnerability Fix Script
# This script updates all packages to fix security vulnerabilities
# Run with: bash fix-vulnerabilities.sh

set -e  # Exit on error

echo "========================================="
echo "BizMatch Security Vulnerability Fix"
echo "========================================="
echo ""

# Fix permissions first
echo "Step 1: Fixing node_modules permissions..."
echo "-------------------------------------------"
cd /home/timo/bizmatch-project/bizmatch-server
if [ -d "node_modules" ]; then
    echo "Removing bizmatch-server/node_modules..."
    rm -rf node_modules package-lock.json || {
        echo "WARNING: Could not remove node_modules due to permissions"
        echo "Please run: sudo rm -rf node_modules package-lock.json"
        echo "Then run this script again"
        exit 1
    }
fi

cd /home/timo/bizmatch-project/bizmatch
if [ -d "node_modules" ]; then
    echo "Removing bizmatch/node_modules..."
    rm -rf node_modules package-lock.json || {
        echo "WARNING: Could not remove node_modules due to permissions"
        echo "Please run: sudo rm -rf node_modules package-lock.json"
        echo "Then run this script again"
        exit 1
    }
fi

echo "✓ Old node_modules removed"
echo ""

# Install bizmatch-server
echo "Step 2: Installing bizmatch-server packages..."
echo "------------------------------------------------"
cd /home/timo/bizmatch-project/bizmatch-server
npm install
echo "✓ bizmatch-server packages installed"
echo ""

# Install bizmatch frontend
echo "Step 3: Installing bizmatch frontend packages..."
echo "---------------------------------------------------"
cd /home/timo/bizmatch-project/bizmatch
npm install
echo "✓ bizmatch frontend packages installed"
echo ""

# Run audits to check remaining vulnerabilities
echo "Step 4: Checking remaining vulnerabilities..."
echo "----------------------------------------------"
cd /home/timo/bizmatch-project/bizmatch-server
echo ""
echo "=== bizmatch-server audit ==="
npm audit --production 2>&1 || true
echo ""

cd /home/timo/bizmatch-project/bizmatch
echo ""
echo "=== bizmatch frontend audit ==="
npm audit --production 2>&1 || true
echo ""

echo "========================================="
echo "✓ Vulnerability fixes completed!"
echo "========================================="
echo ""
echo "Summary of changes:"
echo "  - Updated Angular 18 → 19 (fixes XSS vulnerabilities)"
echo "  - Updated nodemailer 6 → 7 (fixes DoS vulnerabilities)"
echo "  - Updated @nestjs-modules/mailer 2.0 → 2.1 (fixes mjml vulnerabilities)"
echo "  - Updated drizzle-kit 0.23 → 0.31 (fixes esbuild vulnerabilities)"
echo "  - Updated firebase 11.3 → 11.9 (fixes undici vulnerabilities)"
echo ""
echo "NOTE: Some dev-only vulnerabilities may remain (esbuild, tmp)"
echo "These do NOT affect production builds."
echo ""
