#!/bin/bash
# Fix rembg service for birefnet — increase timeout and worker settings
cat > /etc/systemd/system/rembg.service << 'EOF'
[Unit]
Description=rembg Background Removal Service
After=network.target

[Service]
Type=simple
ExecStart=/usr/local/bin/rembg s --port 5100 --threads 1
Restart=always
RestartSec=10
MemoryMax=12G
Environment=U2NET_HOME=/root/.u2net
Environment=UVICORN_TIMEOUT_KEEP_ALIVE=120

[Install]
WantedBy=multi-target
EOF

# Also set uvicorn timeout via wrapper
cat > /usr/local/bin/rembg-server.sh << 'SCRIPT'
#!/bin/bash
export U2NET_HOME=/root/.u2net
exec python3 -m uvicorn rembg.commands.s_command:app --host 0.0.0.0 --port 5100 --workers 1 --timeout-keep-alive 120
SCRIPT
chmod +x /usr/local/bin/rembg-server.sh

# Update service to use the wrapper with longer timeout
cat > /etc/systemd/system/rembg.service << 'EOF'
[Unit]
Description=rembg Background Removal Service
After=network.target

[Service]
Type=simple
ExecStart=/usr/local/bin/rembg s --port 5100 --threads 1
Restart=always
RestartSec=10
MemoryMax=12G
TimeoutStartSec=120
Environment=U2NET_HOME=/root/.u2net

[Install]
WantedBy=multi-user.target
EOF

systemctl daemon-reload
systemctl restart rembg
echo "Done - waiting 30s for model load..."
sleep 30
echo "Testing..."
curl -s -o /dev/null -w "HTTP %{http_code}\n" http://localhost:5100/api/remove
