#!/bin/bash
# SSH Key Maintenance and Backup Script
# Run this periodically to maintain key security

echo "🔧 SSH Key Maintenance and Backup"

# Check if NAS is mounted
if [ ! -d "/mnt/NV2" ]; then
    echo "❌ ERROR: NAS not mounted at /mnt/NV2"
    exit 1
fi

# Create timestamp
TIMESTAMP=$(date +%Y%m%d-%H%M%S)
BACKUP_ROOT="/mnt/NV2/ssh-keys"
BACKUP_DIR="$BACKUP_ROOT/maintenance-$TIMESTAMP"

# Ensure backup directory structure
mkdir -p "$BACKUP_DIR"
chmod 700 "$BACKUP_DIR"

echo "📁 Creating maintenance backup in: $BACKUP_DIR"

# Backup current keys and config
cp ~/.ssh/*_rsa* "$BACKUP_DIR/" 2>/dev/null || true
cp ~/.ssh/config "$BACKUP_DIR/" 2>/dev/null || true
cp ~/.ssh/known_hosts "$BACKUP_DIR/" 2>/dev/null || true

# Check key ages and recommend rotation
echo ""
echo "🔍 Key Age Analysis:"
for key in ~/.ssh/*_rsa; do
    if [ -f "$key" ]; then
        age_days=$(( ($(date +%s) - $(stat -c %Y "$key")) / 86400 ))
        basename_key=$(basename "$key")
        
        if [ $age_days -gt 365 ]; then
            echo "⚠️  $basename_key: $age_days days old - ROTATION RECOMMENDED"
        elif [ $age_days -gt 180 ]; then
            echo "⚡ $basename_key: $age_days days old - consider rotation"
        else
            echo "✅ $basename_key: $age_days days old - OK"
        fi
    fi
done

# Test key accessibility
echo ""
echo "🔐 Testing Key Access:"
for key in ~/.ssh/*_rsa; do
    if [ -f "$key" ]; then
        basename_key=$(basename "$key")
        if ssh-keygen -l -f "$key" >/dev/null 2>&1; then
            echo "✅ $basename_key: Valid and readable"
        else
            echo "❌ $basename_key: CORRUPTED or unreadable"
        fi
    fi
done

# Clean up old backups (keep last 10)
echo ""
echo "🧹 Cleaning old backups (keeping last 10):"
cd "$BACKUP_ROOT"
ls -dt backup-* maintenance-* 2>/dev/null | tail -n +11 | while read old_backup; do
    if [ -d "$old_backup" ]; then
        echo "🗑️  Removing old backup: $old_backup"
        rm -rf "$old_backup"
    fi
done

# Generate maintenance report
cat > "$BACKUP_DIR/MAINTENANCE_REPORT.md" << EOF
# SSH Key Maintenance Report
Generated: $(date)
Host: $(hostname)
User: $(whoami)

## Backup Location
$BACKUP_DIR

## Key Inventory
$(ls -la ~/.ssh/*_rsa* 2>/dev/null || echo "No SSH keys found")

## SSH Config Status
$(if [ -f ~/.ssh/config ]; then echo "SSH config exists: ~/.ssh/config"; else echo "No SSH config found"; fi)

## Server Connection Tests
Run these commands to verify connectivity:

### Primary Keys:
ssh -o ConnectTimeout=5 database-apis 'echo "DB APIs: OK"'
ssh -o ConnectTimeout=5 pihole 'echo "PiHole: OK"'
ssh -o ConnectTimeout=5 akamai 'echo "Akamai: OK"'

### Emergency Keys (if deployed):
ssh -i ~/.ssh/emergency_homelab_rsa -o ConnectTimeout=5 cal@10.10.0.16 'echo "Emergency Home: OK"'
ssh -i ~/.ssh/emergency_cloud_rsa -o ConnectTimeout=5 root@172.237.147.99 'echo "Emergency Cloud: OK"'

## Next Maintenance Due
$(date -d '+3 months')

## Key Rotation Schedule
- Home lab keys: Annual (generated $(date -r ~/.ssh/homelab_rsa 2>/dev/null || echo "Not found"))
- Cloud keys: Annual (generated $(date -r ~/.ssh/cloud_servers_rsa 2>/dev/null || echo "Not found"))
- Emergency keys: Bi-annual

EOF

echo "✅ Maintenance backup completed"
echo "📄 Report saved: $BACKUP_DIR/MAINTENANCE_REPORT.md"
echo ""
echo "💡 Schedule this script to run monthly via cron:"
echo "   0 2 1 * * /path/to/ssh_key_maintenance.sh"