#!/bin/bash
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 --model birefnet-general
Restart=always
RestartSec=15
Environment=U2NET_HOME=/root/.u2net
LimitNOFILE=65535

[Install]
WantedBy=multi-user.target
EOF

systemctl daemon-reload
systemctl restart rembg
echo "Service restarted with birefnet-general preloaded"
echo "Waiting 45s for model load..."
sleep 45
echo "Testing..."
curl -s -o /dev/null -w "HTTP status: %{http_code}\n" -X POST http://localhost:5100/api/remove
echo "Memory usage:"
ps aux --sort=-rss | head -5
