#!/bin/bash

# Linux Startup Script for Al Mirag Poultry Management
# This script starts the application with proper Linux configurations

set -e

# Colors for output
GREEN='\033[0;32m'
BLUE='\033[0;34m'
RED='\033[0;31m'
NC='\033[0m' # No Color

print_status() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

print_success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
}

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

# Get the directory where the script is located
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
cd "$SCRIPT_DIR"

print_status "Starting Al Mirag Poultry Management on Linux..."

# Set environment variables
export FLASK_ENV=production
export PYTHONPATH="$SCRIPT_DIR"
export PYTHONUNBUFFERED=1

# Create necessary directories
mkdir -p "$SCRIPT_DIR/logs"
mkdir -p "$SCRIPT_DIR/tmp"
mkdir -p "$SCRIPT_DIR/uploads"
mkdir -p "$SCRIPT_DIR/instance"

# Set proper permissions
chmod 755 "$SCRIPT_DIR/logs"
chmod 755 "$SCRIPT_DIR/tmp"
chmod 777 "$SCRIPT_DIR/uploads"
chmod 755 "$SCRIPT_DIR/instance"

# Check if Python is available
if command -v python3 &> /dev/null; then
    PYTHON_CMD="python3"
elif command -v python &> /dev/null; then
    PYTHON_CMD="python"
else
    print_error "Python is not installed. Please install Python 3.7 or higher."
    exit 1
fi

# Check if dependencies are installed
if ! $PYTHON_CMD -c "import flask" &> /dev/null; then
    print_error "Flask is not installed. Please run: pip install -r requirements.txt"
    exit 1
fi

# Initialize database if it doesn't exist
if [ ! -f "$SCRIPT_DIR/instance/poultry.db" ]; then
    print_status "Initializing database..."
    $PYTHON_CMD -c "
import sys
sys.path.insert(0, '$SCRIPT_DIR')
from app import app, db
with app.app_context():
    db.create_all()
    print('Database initialized successfully')
"
fi

# Start the application
print_status "Starting application..."
print_status "Application will be available at: http://localhost:5000"
print_status "Press Ctrl+C to stop the application"

# Start with proper logging
$PYTHON_CMD app.py 2>&1 | tee "$SCRIPT_DIR/logs/app.log"
