#!/bin/bash
# This script sets up the required directories and permissions on the server
# Run this script on the server before deploying

echo "Setting up directories and permissions for img-manager..."

# Create all required directories
mkdir -p /root/img_manager/code
mkdir -p /root/img_manager/storage
mkdir -p /root/img_manager/uploads
mkdir -p /root/img_manager/public/vite
mkdir -p /root/img_manager/node_modules
mkdir -p /root/img_manager/logs
mkdir -p /root/img_manager/tmp

# Set very permissive permissions
chmod -R 777 /root/img_manager

# Create empty database files with proper permissions
touch /root/img_manager/storage/production.sqlite3
touch /root/img_manager/storage/production_cache.sqlite3
touch /root/img_manager/storage/production_queue.sqlite3
touch /root/img_manager/storage/production_cable.sqlite3
chmod 666 /root/img_manager/storage/*.sqlite3

# Initialize the database files with schema_migrations tables
echo "Initializing database files with schema_migrations tables..."
for db_file in /root/img_manager/storage/production.sqlite3 /root/img_manager/storage/production_cache.sqlite3 /root/img_manager/storage/production_queue.sqlite3 /root/img_manager/storage/production_cable.sqlite3; do
  sqlite3 "$db_file" "CREATE TABLE IF NOT EXISTS schema_migrations (version varchar(255) NOT NULL); CREATE UNIQUE INDEX IF NOT EXISTS unique_schema_migrations ON schema_migrations (version);" || echo "Failed to initialize $db_file"
done

echo "Checking SELinux status..."
if command -v getenforce &> /dev/null; then
  selinux_status=$(getenforce)
  echo "SELinux status: $selinux_status"
  
  if [ "$selinux_status" == "Enforcing" ]; then
    echo "SELinux is enforcing. Setting proper contexts..."
    # Set SELinux context for the directories
    if command -v chcon &> /dev/null; then
      chcon -Rt svirt_sandbox_file_t /root/img_manager
    else
      echo "chcon command not found. Unable to set SELinux context."
    fi
  fi
else
  echo "getenforce command not found. Unable to check SELinux status."
fi

echo "Directory permissions:"
ls -la /root/img_manager

echo "Storage directory permissions:"
ls -la /root/img_manager/storage

echo "Setup complete!"