#!/bin/bash

DAEMON=/usr/local/sbin/backupperd
PIDFILE=/run/backupper/backupper.pid
LOGFILE=/var/log/backupper.log

start() {
  mkdir -p /run/backupper /var/lib/backupper /boot/config/plugins/backupper
  chmod 0750 /run/backupper /var/lib/backupper
  chmod 0700 /boot/config/plugins/backupper
  if [ -s "$PIDFILE" ] && kill -0 "$(cat "$PIDFILE")" 2>/dev/null; then
    return 0
  fi
  nohup "$DAEMON" >>"$LOGFILE" 2>&1 &
  echo $! >"$PIDFILE"
}

stop() {
  if [ -s "$PIDFILE" ]; then
    PID=$(cat "$PIDFILE")
    kill "$PID" 2>/dev/null || true
    for _ in $(seq 1 30); do
      kill -0 "$PID" 2>/dev/null || break
      sleep 1
    done
    kill -9 "$PID" 2>/dev/null || true
    rm -f "$PIDFILE"
  fi
}

case "${1:-}" in
  start) start ;;
  stop) stop ;;
  restart) stop; start ;;
  status)
    if [ -s "$PIDFILE" ] && kill -0 "$(cat "$PIDFILE")" 2>/dev/null; then echo "backupperd is running"; else echo "backupperd is stopped"; exit 1; fi
    ;;
  *) echo "Usage: $0 {start|stop|restart|status}"; exit 2 ;;
esac

