Commit f27720d5 authored by Andreas Düren's avatar Andreas Düren
Browse files

Replace Node.js placeholder with actual Museum server

parent 950481b6
Loading
Loading
Loading
Loading
+68 −134
Original line number Diff line number Diff line
@@ -143,156 +143,90 @@ else
    echo "==> PostgreSQL connection successful"
fi

# Create Node.js placeholder server - we'll use this instead of trying to build with Go
echo "==> Creating Node.js placeholder server..."
cat > /app/data/ente/server/server.js << 'EOF'
const http = require('http');
const fs = require('fs');
const path = require('path');

const PORT = 3080;
const LOG_FILE = '/app/data/logs/museum.log';

// Ensure log directory exists
if (!fs.existsSync('/app/data/logs')) {
  fs.mkdirSync('/app/data/logs', { recursive: true });
}
# Build and run the Museum server
echo "==> Setting up Museum server..."

// Log function
function log(message) {
  const timestamp = new Date().toISOString();
  const logMessage = `${timestamp} - ${message}\n`;
  console.log(logMessage);
  try {
    fs.appendFileSync(LOG_FILE, logMessage);
  } catch (err) {
    console.error(`Error writing to log: ${err.message}`);
  }
}
# Set GOPATH for Go builds
export GOPATH="/app/data/go"
export PATH="$GOPATH/bin:$PATH"

log('Starting Node.js placeholder server...');
# Check for existing Museum binary
MUSEUM_BIN="/app/data/ente/server/museum"
if [ -f "$MUSEUM_BIN" ] && [ -x "$MUSEUM_BIN" ]; then
    echo "==> Found existing Museum binary, using it"
else
    echo "==> Building Museum server from source..."
    
// Create server
const server = http.createServer((req, res) => {
  log(`Request received: ${req.method} ${req.url}`);
    # Install required build dependencies
    echo "==> Installing build dependencies..."
    apt-get update -y && apt-get install -y golang-go gcc libsodium-dev pkg-config
    
  // Set CORS headers for all responses
  res.setHeader('Access-Control-Allow-Origin', '*');
  res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
  res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type,Authorization');
    # Navigate to the server directory
    cd "$ENTE_DIR/server"
    
  // Handle OPTIONS request (for CORS preflight)
  if (req.method === 'OPTIONS') {
    res.writeHead(200);
    res.end();
    return;
  }
    # Build the Museum server
    echo "==> Building Museum server..."
    go build -o "$MUSEUM_BIN" ./cmd/museum
    
  // Health check endpoint
  if (req.url === '/health' || req.url === '/api/health') {
    res.writeHead(200, { 'Content-Type': 'application/json' });
    res.end(JSON.stringify({ status: 'OK', server: 'Museum Placeholder' }));
    log('Health check request - responded with status OK');
    return;
  }
    if [ $? -ne 0 ]; then
        echo "==> Failed to build Museum server from source"
        echo "==> Trying to download pre-built binary..."
        
  // Authentication endpoints
  if (req.url === '/api/users/verify') {
    res.writeHead(200, { 'Content-Type': 'application/json' });
    log('User verify request - responding with success');
    res.end(JSON.stringify({ 
      success: true,
      isValidEmail: true,
      isAvailable: true,
      isVerified: true,
      canCreateAccount: true
    }));
    return;
  }
        # Determine architecture and platform
        ARCH=$(uname -m)
        OS=$(uname -s | tr '[:upper:]' '[:lower:]')
        
  // Handle all API requests with a generic success response
  if (req.url.startsWith('/api/')) {
    res.writeHead(200, { 'Content-Type': 'application/json' });
    log(`API request to ${req.url} - responding with generic success`);
    res.end(JSON.stringify({ 
      success: true,
      message: 'Placeholder API response',
      path: req.url 
    }));
    return;
  }
        case "$ARCH" in
            x86_64)
                ARCH="amd64"
                ;;
            aarch64|arm64)
                ARCH="arm64"
                ;;
        esac
        
  // Default response for any other endpoint
  res.writeHead(200, { 'Content-Type': 'application/json' });
  log(`Unknown request to ${req.url} - responding with default message`);
  res.end(JSON.stringify({ 
    message: 'Placeholder Museum Server', 
    path: req.url,
    server: 'Node.js Placeholder'
  }));
});

// Start server
try {
  server.listen(PORT, '0.0.0.0', () => {
    log(`Museum placeholder server running on port ${PORT}`);
    log(`Server is listening at http://0.0.0.0:${PORT}`);
  });
} catch (err) {
  log(`Failed to start server: ${err.message}`);
  process.exit(1);
}

// Handle errors
server.on('error', (error) => {
  log(`Server error: ${error.message}`);
  if (error.code === 'EADDRINUSE') {
    log('Address already in use, retrying in 5 seconds...');
    setTimeout(() => {
      server.close();
      server.listen(PORT, '0.0.0.0');
    }, 5000);
  }
});
        MUSEUM_URL="https://github.com/ente-io/ente/releases/latest/download/museum-${OS}-${ARCH}"
        curl -L -o "$MUSEUM_BIN" "$MUSEUM_URL"
        
// Log startup
log('Museum placeholder server initialization complete');
EOF
echo "==> Created Node.js placeholder server"
        if [ $? -ne 0 ]; then
            echo "==> Failed to download pre-built binary"
            exit 1
        else
            chmod +x "$MUSEUM_BIN"
            echo "==> Downloaded pre-built Museum binary"
        fi
    else
        chmod +x "$MUSEUM_BIN"
        echo "==> Successfully built Museum server"
    fi
fi

# Start Node.js placeholder server
echo "==> Starting Node.js placeholder server..."
# Start the Museum server
echo "==> Starting Museum server..."
cd /app/data/ente/server
node server.js > /app/data/logs/museum_startup.log 2>&1 &
SERVER_PID=$!
echo "==> Started Node.js server with PID: $SERVER_PID"
"$MUSEUM_BIN" --config "$MUSEUM_CONFIG" > /app/data/logs/museum.log 2>&1 &
MUSEUM_PID=$!
echo "==> Started Museum server with PID: $MUSEUM_PID"

# Wait for server to start
MAX_ATTEMPTS=30
ATTEMPT=0
while [ $ATTEMPT -lt $MAX_ATTEMPTS ]; do
    if curl -s http://localhost:3080/health > /dev/null; then
        echo "==> Node.js placeholder server started successfully"
        echo "==> Museum server started successfully"
        break
    fi
    ATTEMPT=$((ATTEMPT+1))
    echo "==> Waiting for Node.js server to start (attempt $ATTEMPT/$MAX_ATTEMPTS)..."
    echo "==> Waiting for Museum server to start (attempt $ATTEMPT/$MAX_ATTEMPTS)..."
    sleep 1
done

if [ $ATTEMPT -eq $MAX_ATTEMPTS ]; then
    echo "==> ERROR: Node.js server failed to start within $MAX_ATTEMPTS seconds"
    echo "==> Last few lines of museum_startup.log:"
    tail -n 20 /app/data/logs/museum_startup.log || echo "==> No log file found"
    
    # Check if the process is still running
    if kill -0 $SERVER_PID 2>/dev/null; then
        echo "==> Process is still running, but not responding to health checks"
    else
        echo "==> Process is not running. Attempting to restart..."
        node /app/data/ente/server/server.js > /app/data/logs/museum.log 2>&1 &
        echo "==> Restarted Node.js server"
    fi
    echo "==> ERROR: Museum server failed to start within $MAX_ATTEMPTS seconds"
    echo "==> Last few lines of museum.log:"
    tail -n 20 /app/data/logs/museum.log || echo "==> No log file found"
    echo "==> Aborting startup"
    exit 1
fi

# Download and set up web app
@@ -441,7 +375,7 @@ echo "==> Setup complete, everything is running."

# Verify services are running
echo "==> Verifying services..."
ps aux | grep node | grep -v grep || echo "WARNING: Node.js server not running!"
ps aux | grep museum | grep -v grep || echo "WARNING: Museum server not running!"
ps aux | grep caddy | grep -v grep || echo "WARNING: Caddy server not running!"

# Keep script running