#!/usr/bin/env bash
set -euo pipefail

APP_DIR="/opt/esn-api"
SERVICE_NAME="esn-api"

if [ ! -d "$APP_DIR" ]; then
  echo "Missing $APP_DIR. Create it first and upload project files."
  exit 1
fi

cd "$APP_DIR"

if [ ! -f ".env" ]; then
  echo "Missing .env in $APP_DIR"
  echo "Copy .env.production.example to .env and set secrets before deploy."
  exit 1
fi

npm install --omit=dev
node src/migrate.js

sudo cp deploy/systemd/esn-api.service /etc/systemd/system/esn-api.service
sudo systemctl daemon-reload
sudo systemctl enable "$SERVICE_NAME"
sudo systemctl restart "$SERVICE_NAME"
sudo systemctl --no-pager --full status "$SERVICE_NAME" | head -n 40

echo "Deploy update complete."
