#!/bin/sh

# Ensure data directory exists with proper permissions
mkdir -p /app/data
chown -R nodejs:nodejs /app/data

# Ensure uploads directory exists with proper permissions (after volume mount)
mkdir -p /app/uploads
chown -R nodejs:nodejs /app/uploads
chmod 755 /app/uploads

# Set database path to data directory
export DATABASE_URL="file:/app/data/prod.db"

# Run Prisma migrations (as root, then switch to nodejs)
echo "Running database migrations..."
npx prisma db push --skip-generate || echo "Database push failed, will try on startup..."

# Fix database file permissions after creation
if [ -f /app/data/prod.db ]; then
  chown nodejs:nodejs /app/data/prod.db
  chmod 664 /app/data/prod.db
fi

# Log uploads directory status
echo "Uploads directory status:"
ls -la /app/uploads || echo "Uploads directory does not exist"

# Start the application as nodejs user
echo "Starting application..."
exec su-exec nodejs npx tsx src/index.ts
