#!/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
  rm -f "$PIDFILE" /run/backupper/backupper.sock
  nohup "$DAEMON" >>"$LOGFILE" 2>&1 &
  echo $! >"$PIDFILE"
}

stop() {
  STOPPED=0
  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"
    STOPPED=1
  fi
  if [ "$STOPPED" -eq 0 ]; then
    PIDS=$(pidof backupperd 2>/dev/null || true)
    for PID in $PIDS; do
      kill "$PID" 2>/dev/null || true
    done
    for _ in $(seq 1 30); do
      [ -z "$(pidof backupperd 2>/dev/null)" ] && break
      sleep 1
    done
    for PID in $(pidof backupperd 2>/dev/null); do
      kill -9 "$PID" 2>/dev/null || true
    done
  fi
  rm -f /run/backupper/backupper.sock
}

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
