#!/bin/bash
# ============================================================
# 04_service.sh
# Creates systemd service so FastAPI starts on boot
# Run as root AFTER 02_deploy.sh
# ============================================================
set -e

DEPLOY_DIR="/var/www/html/me.goteku.com"

echo "=== Creating systemd service ==="
cat > /etc/systemd/system/me-goteku-backend.service <<EOF
[Unit]
Description=me.goteku.com FastAPI Backend
After=network.target postgresql.service

[Service]
Type=simple
WorkingDirectory=${DEPLOY_DIR}/backend
EnvironmentFile=${DEPLOY_DIR}/backend/.env
ExecStart=${DEPLOY_DIR}/backend/venv/bin/uvicorn app.main:app --host 127.0.0.1 --port 8002
Restart=always
RestartSec=5
StandardOutput=journal
StandardError=journal

[Install]
WantedBy=multi-user.target
EOF

echo "=== Enabling and starting service ==="
systemctl daemon-reload
systemctl enable me-goteku-backend
systemctl start me-goteku-backend

sleep 2
systemctl status me-goteku-backend --no-pager

echo ""
echo "✅ Backend service running"
echo "   Check logs: journalctl -u me-goteku-backend -f"
