#!/bin/bash

# Ginxsom Database Initialization Script
# This script creates the SQLite database with the proper schema

set -e  # Exit on any error

# Configuration
DB_DIR="$(dirname "$0")"
DB_FILE="$DB_DIR/ginxsom.db"
SCHEMA_FILE="$DB_DIR/schema.sql"

echo "Initializing Ginxsom database..."

# Check if schema file exists
if [ ! -f "$SCHEMA_FILE" ]; then
    echo "Error: Schema file not found at $SCHEMA_FILE"
    exit 1
fi

# Create database directory if it doesn't exist
mkdir -p "$DB_DIR"

# Remove existing database if it exists (for clean initialization)
if [ -f "$DB_FILE" ]; then
    echo "Warning: Existing database found. Creating backup..."
    cp "$DB_FILE" "$DB_FILE.backup.$(date +%s)"
    rm "$DB_FILE"
fi

# Create new database with schema
echo "Creating database at $DB_FILE..."
sqlite3 "$DB_FILE" < "$SCHEMA_FILE"

# Set proper permissions
chmod 644 "$DB_FILE"
chmod 755 "$DB_DIR"

echo "Database initialized successfully!"
echo "Database location: $DB_FILE"

# Show database info
echo ""
echo "Database tables:"
sqlite3 "$DB_FILE" ".tables"

echo ""
echo "Server configuration:"
sqlite3 "$DB_FILE" "SELECT key, value, description FROM server_config;"

echo ""
echo "Database ready for use."
