#!/bin/sh
set -eu
APP_DIR="/share/homes/mailcat/mailcat"
ACCOUNT="backup"
PYTHON="/opt/bin/python3"
STATE_DIR="/share/homes/mailcat/mailcat/state"
LOG_DIR="/share/homes/mailcat/mailcat/log"
RUN_DIR="/share/homes/mailcat/mailcat/run"
PID_FILE="/share/homes/mailcat/mailcat/run/mailcat.pid"
MKDIR="/bin/mkdir"

"$MKDIR" -p "$STATE_DIR" "$LOG_DIR" "$RUN_DIR"
if [ -f "$PID_FILE" ]; then
  old_pid=""
  IFS= read -r old_pid < "$PID_FILE" || true
  if [ -n "$old_pid" ] && kill -0 "$old_pid" 2>/dev/null; then
    echo "mailcat already running: $old_pid"
    exit 0
  fi
fi

cd "$APP_DIR"
"$PYTHON" "$APP_DIR/sort_mail_daemon.py" --account "$ACCOUNT" --folder INBOX --state-file "$STATE_DIR/sort_mail_daemon_state.json" --log-file "$LOG_DIR/sort_mail_daemon.log" >> "$LOG_DIR/daemon.out" 2>&1 &
pid="$!"
echo "$pid" > "$PID_FILE"
echo "mailcat started: $pid"
