#!/bin/sh
# fillrate-task: vast-daemon-restart
# Restarts vastai.service.
# Refuses while any container is running unless FILLRATE_OVERRIDE=1.
# The runner sets FILLRATE_OVERRIDE from the ticket. It is not taken from the host environment
# when the runner starts the task, because the runner clears the environment first.

set -u

override="${FILLRATE_OVERRIDE:-0}"

if command -v docker >/dev/null 2>&1; then
  ids=$(docker ps -q) || {
    echo "docker ps failed; refusing to restart"
    exit 1
  }
  count=$(printf '%s\n' "$ids" | grep -c . || true)
  if [ "$count" != "0" ] && [ "$override" != "1" ]; then
    echo "refusing: containers are running and the ticket has no override"
    exit 2
  fi
  if [ "$count" != "0" ]; then
    echo "override set; restarting with containers running"
  fi
else
  echo "docker not found; treating that as no rental containers"
fi

if ! command -v systemctl >/dev/null 2>&1; then
  echo "systemctl not found"
  exit 1
fi

systemctl restart vastai.service
restart_code=$?
if [ "$restart_code" -ne 0 ]; then
  echo "systemctl restart vastai.service failed ($restart_code)"
  exit "$restart_code"
fi

if systemctl is-active --quiet vastai.service; then
  echo "vastai.service is active"
  systemctl status vastai.service --no-pager || true
  exit 0
fi

echo "vastai.service did not become active"
systemctl status vastai.service --no-pager || true
exit 1
