#!/bin/bash
#
# AtlasOS - Calypso Migration Check Script
# Checks if zfs_datasets table exists and shows migration status
#

set -euo pipefail

GREEN='\033[0;32m'
YELLOW='\033[1;33m'
RED='\033[0;31m'
NC='\033[0m'

log_info() {
    echo -e "${GREEN}[INFO]${NC} $1"
}

log_warn() {
    echo -e "${YELLOW}[WARN]${NC} $1"
}

log_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# Check if running as root
if [ "$EUID" -ne 0 ]; then 
    log_error "Please run as root (use sudo)"
    exit 1
fi

log_info "Checking migration status..."

# Check if table exists
if sudo -u postgres psql -d calypso -c "\d zfs_datasets" > /dev/null 2>&1; then
    log_info "✓ Table zfs_datasets exists"
    sudo -u postgres psql -d calypso -c "\d zfs_datasets" | head -30
else
    log_warn "✗ Table zfs_datasets does not exist"
    log_info "Checking applied migrations..."
    
    # Check applied migrations
    if sudo -u postgres psql -d calypso -c "SELECT version FROM schema_migrations ORDER BY version;" 2>/dev/null; then
        log_info ""
        log_info "Migration 005 should create zfs_datasets table"
        log_info "Please restart the API service to run migrations:"
        log_info "  sudo systemctl restart calypso-api"
    else
        log_error "Cannot connect to database"
        exit 1
    fi
fi

log_info ""
log_info "Done!"

