#!/bin/bash

# Startup script for Docker containers to ensure permissions and run tests

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

echo -e "${BLUE}=== Container Startup Checks ===${NC}"

# Display system information
echo -e "${BLUE}System information:${NC}"
if [ -f /etc/os-release ]; then
    . /etc/os-release
    echo -e "- OS: ${GREEN}$PRETTY_NAME${NC}"
else
    echo -e "- OS: ${YELLOW}Unknown${NC}"
fi

# Ensure packages.list is available
echo -e "${BLUE}Checking for packages.list:${NC}"
if [ -f "$HOME/shell/setup/packages.list" ]; then
    echo -e "- packages.list: ${GREEN}Found${NC}"
    # Count packages in list (excluding comments and empty lines)
    pkg_count=$(grep -v '^//' "$HOME/shell/setup/packages.list" | grep -v -e '^$' | sed 's|//.*||' | awk '{print $1}' | grep -v '^$' | wc -l)
    echo -e "- Package count: ${GREEN}$pkg_count packages${NC}"
else
    echo -e "- packages.list: ${RED}Not found${NC}"
    echo "Error: Could not find packages.list file. Tests will fail."
fi

# Ensure logs directory has correct permissions
echo -e "${BLUE}Setting up logs directory:${NC}"
if [ -d "/logs" ]; then
    echo -e "- Logs directory: ${GREEN}Found${NC}"

    # Check ownership and permissions
    logs_owner=$(stat -c '%U:%G' /logs)
    echo -e "- Current ownership: $logs_owner"

    echo "- Setting permissions on /logs directory..."
    sudo chown -R $(whoami):$(whoami) /logs 2>/dev/null || echo -e "${YELLOW}Failed to set ownership${NC}"
    sudo chmod -R 755 /logs 2>/dev/null || echo -e "${YELLOW}Failed to set directory permissions${NC}"
    # Set appropriate permissions for log files (644)
    sudo find /logs -type f -exec chmod 644 {} \; 2>/dev/null || echo -e "${YELLOW}Failed to set file permissions${NC}"

    # Verify permissions are correct
    if [ -w "/logs" ]; then
        echo -e "- Write permission: ${GREEN}OK${NC}"

        # Create a test file to really verify we can write
        if touch "/logs/test_file" 2>/dev/null; then
            echo -e "- Test write: ${GREEN}Succeeded${NC}"
            rm -f "/logs/test_file"
        else
            echo -e "- Test write: ${RED}Failed${NC}"
        fi
    else
        echo -e "- Write permission: ${RED}Failed${NC}"
    fi
else
    echo -e "- Logs directory: ${YELLOW}Not found${NC}"
    echo "- Creating /logs directory..."
    if sudo mkdir -p /logs && sudo chown -R $(whoami):$(whoami) /logs && sudo chmod -R 755 /logs; then
        echo -e "- Created logs directory with proper permissions: ${GREEN}Success${NC}"
        # Ensure future log files get proper permissions
        sudo find /logs -type f -exec chmod 644 {} \; 2>/dev/null || true
    else
        echo -e "- Creating logs directory: ${RED}Failed${NC}"
        echo "Warning: Logs will be saved inside container only"
    fi
fi

echo -e "${BLUE}=== Starting Test Script ===${NC}"
# Run the test script
"$HOME/shell/setup/test-setup.sh"
