#!/bin/bash
set -e

echo "Deploying React application using volume mounts..."

# Check if React app is already built
if [ ! -d ~/server-setup/well_mob_pwa/build ]; then
  echo "React build directory not found. Building React application..."
  cd ~/server-setup/well_mob_pwa
  
  # Set environment variables to bypass TypeScript errors
  export CI=false
  export TSC_COMPILE_ON_ERROR=true
  export ESLINT_NO_DEV_ERRORS=true
  export DISABLE_ESLINT_PLUGIN=true
  
  # Build the React app
  npm run build
  
  # Check if build was successful
  if [ ! -d "build" ]; then
    echo "React build failed. Please check the errors."
    exit 1
  fi
  echo "React build completed successfully."
  cd ~/server-setup
else
  echo "Using existing React build directory."
fi

# Return to server-setup directory
cd ~/server-setup

# Ensure we have the Nginx config for the React app
if [ ! -f ./nginx/conf.d/react.conf ]; then
  echo "Creating Nginx configuration for React app..."
  mkdir -p ./nginx/conf.d
  
  # Try with sudo if needed
  if ! cat > ./nginx/conf.d/react.conf << 'EOL'
server {
    listen 80;
    server_name react.eluxnetworks.net;

    location / {
        root /usr/share/nginx/html/react;
        try_files $uri $uri/ /index.html;
        add_header Cache-Control "no-cache, no-store, must-revalidate";
    }

    # For static assets
    location /assets/ {
        root /usr/share/nginx/html/react;
        expires 1y;
        add_header Cache-Control "public, max-age=31536000";
        access_log off;
    }
}
EOL
  then
    echo "Permission denied. Trying with sudo..."
    sudo tee ./nginx/conf.d/react.conf > /dev/null << 'EOL'
server {
    listen 80;
    server_name react.eluxnetworks.net;

    location / {
        root /usr/share/nginx/html/react;
        try_files $uri $uri/ /index.html;
        add_header Cache-Control "no-cache, no-store, must-revalidate";
    }

    # For static assets
    location /assets/ {
        root /usr/share/nginx/html/react;
        expires 1y;
        add_header Cache-Control "public, max-age=31536000";
        access_log off;
    }
}
EOL
  fi
fi

# Update permissions for acme.json if needed
if [ -f acme.json ]; then
  chmod 600 acme.json
fi

echo "Restarting Docker containers..."
docker compose down
docker compose up -d

# Check container status
echo "Checking container status..."
sleep 5
docker compose ps

echo "React application deployment completed."
echo "Please verify that all sites are working correctly:"
echo "- http://eluxnetworks.net/"
echo "- https://eluxnetworks.net/"
echo "- https://eluxnetworks.net/well_tests/ (user: well_tester, pass: TestWell_2025)"
echo "- https://eluxnetworks.net/shared/"
echo "- https://react.eluxnetworks.net/assets/login-backgroud.png"