#!/bin/sh
# cronedit: CronEdit's schedule lines, kept in the package's own file and written into /etc/config/crontab.
#
#   cronedit add "<min> <hour> <day> <month> <weekday> <command>"
#   cronedit list
#   cronedit remove <number>
#
# The service script also calls:
#   cronedit sync      bring /etc/config/crontab in line with the package's file (start)
#   cronedit cleanup   take every tagged line out of /etc/config/crontab (stop, uninstall)
#   cronedit check     exit 0 when /etc/config/crontab is in line (status)
#
# The rules (QNAP's for cron, see .claude/skills/qnap-dev/references/nas-shell.md):
# - only /etc/config/crontab is written, the file that outlives a reboot; never crontab -e, /tmp/cron or
#   /var/spool/cron;
# - every line written there ends with TAG, and only lines that end with TAG are ever changed or removed;
# - a line is added only when /etc/config/crontab does not have it yet: never a duplicate;
# - after a change, and only then: crontab /etc/config/crontab && /etc/init.d/crond.sh restart.
#
# POSIX sh for the NAS's BusyBox ash; every program by a full PATH of the firmware's folders.
# BVS_QPKG_SYSROOT is empty on the NAS; a test points it at a scratch folder.

PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
export PATH
umask 022

NAME=CronEdit
TAG_WORD='managed-by:CronEdit'
TAG="# $TAG_WORD" # the end of every line CronEdit writes; a user's line may not hold TAG_WORD
SYS=${BVS_QPKG_SYSROOT-}
CONF=$SYS/etc/config/qpkg.conf
CRONTAB=$SYS/etc/config/crontab
STARTED=$SYS/var/run/$NAME.lock # bvs-qpkg.sh's lock: there from start to stop

say() { echo "cronedit: $*" >&2; }
die() {
  say "$*"
  exit 1
}

event() { # event 0|1|2 TEXT: a line in System Logs too
  if [ -x "$SYS/sbin/log_tool" ]; then
    "$SYS/sbin/log_tool" -t "$1" -a "$NAME: $2" >/dev/null 2>&1
  fi
  return 0
}

ROOT=${QPKG_ROOT-}
if [ -z "$ROOT" ]; then
  ROOT=$("$SYS/sbin/getcfg" "$NAME" Install_Path -f "$CONF" 2>/dev/null)
fi
[ -n "$ROOT" ] && [ -d "$ROOT" ] || die "$NAME is not installed ($CONF names no Install_Path)."
LINES=$ROOT/cronedit.tab # the package's own lines, one cron line per line
VAR=$ROOT/var
LOCK=$VAR/cronedit.lock

# ── the lock: one cronedit at a time changes the files ───────────────────────────────────────────────────────────

unlock() { rm -rf "$LOCK"; }

lock() {
  local n=0 pid
  [ -d "$VAR" ] || mkdir -p "$VAR" || die "cannot make $VAR"
  while ! mkdir "$LOCK" 2>/dev/null; do
    pid=
    read -r pid 2>/dev/null <"$LOCK/pid"
    # its cronedit was killed (with no pid in it after 3 s: killed between mkdir and the pid)
    if { [ -n "$pid" ] && [ ! -d "/proc/$pid" ]; } || { [ -z "$pid" ] && [ "$n" -ge 3 ]; }; then
      rm -rf "$LOCK"
      continue
    fi
    n=$((n + 1))
    [ "$n" -le 30 ] || die "another cronedit holds $LOCK; try again later"
    sleep 1
  done
  echo $$ >"$LOCK/pid"
  trap 'unlock' EXIT
  trap 'exit 1' HUP INT TERM
}

# ── one line ─────────────────────────────────────────────────────────────────────────────────────────────────────

# parse LINE: sets LINE_OUT (the five fields and the command, one space between the fields) or ERR (why not).
parse() {
  local rest=$1 f i=1 fields=
  LINE_OUT=
  ERR=
  case $rest in
    *'
'* | *"$(printf '\r')"*)
      ERR="the line holds a line break"
      return 1
      ;;
  esac
  while [ "$i" -le 5 ]; do
    rest=${rest#"${rest%%[! 	]*}"}
    f=${rest%%[ 	]*}
    if [ -z "$f" ]; then
      ERR="it needs five time fields and a command"
      return 1
    fi
    case $i:$f in
      1:@* | 1:\#*)
        ERR="it must start with the five time fields (no @reboot, no comment)"
        return 1
        ;;
      [123]:*[!0-9*,/-]*)
        ERR="time field $i ('$f') may hold only digits and * , / -"
        return 1
        ;;
      [45]:*[!0-9A-Za-z*,/-]*)
        ERR="time field $i ('$f') may hold only digits, names and * , / -"
        return 1
        ;;
    esac
    fields="$fields$f "
    rest=${rest#"$f"}
    i=$((i + 1))
  done
  rest=${rest#"${rest%%[! 	]*}"}
  rest=${rest%"${rest##*[! 	]}"}
  if [ -z "$rest" ]; then
    ERR="the command is missing after the five time fields"
    return 1
  fi
  case $rest in
    *"$TAG_WORD"*)
      ERR="the command must not hold CronEdit's tag"
      return 1
      ;;
    *\\)
      ERR="the command must not end with a backslash (it would swallow the tag)"
      return 1
      ;;
  esac
  LINE_OUT="$fields$rest"
}

# ── the package's own file ───────────────────────────────────────────────────────────────────────────────────────

# blank LINE: LINE is empty or only blanks (such lines of the package's file are not counted).
blank() {
  case $1 in
    *[!\ \	]*) return 1 ;;
  esac
  return 0
}

# want FILE: FILE gets the tagged form of each valid line of the package's file, in order, each once.
want() {
  local l n=0
  : >"$1" || return 1
  [ -f "$LINES" ] || return 0
  while IFS= read -r l || [ -n "$l" ]; do
    blank "$l" && continue
    n=$((n + 1))
    if ! parse "$l"; then
      say "line $n of $LINES is skipped: $ERR"
      event 1 "line $n of $LINES is skipped: $ERR"
      continue
    fi
    printf '%s\n' "$LINE_OUT $TAG" >>"$1" || return 1
  done <"$LINES"
}

# ── /etc/config/crontab ──────────────────────────────────────────────────────────────────────────────────────────

AWK_OURS='function ours(l) { return length(l) >= length(tag) && substr(l, length(l) - length(tag) + 1) == tag }'

reload() {
  # on the NAS: /usr/bin/crontab /etc/config/crontab && /etc/init.d/crond.sh restart
  if "$SYS/usr/bin/crontab" "$CRONTAB" && "$SYS/etc/init.d/crond.sh" restart >/dev/null 2>&1; then
    return 0
  fi
  say "the reload of cron failed (crontab /etc/config/crontab && /etc/init.d/crond.sh restart)"
  event 2 "the reload of cron failed (crontab /etc/config/crontab && /etc/init.d/crond.sh restart)"
  return 1
}

# apply WANTFILE: /etc/config/crontab keeps every line without TAG as it is and where it is; of the lines with TAG it
# keeps the first copy of each line in WANTFILE and drops the rest; each line of WANTFILE it does not have yet goes
# at its end. Cron is reloaded only when the file changed.
apply() {
  local want=$1 new=$VAR/crontab.new keep=$VAR/crontab.before old=$CRONTAB changes
  [ -f "$old" ] || old=/dev/null
  rm -f "$keep"
  : >"$new" || return 1
  changes=$(awk -v tag="$TAG" -v out="$new" "$AWK_OURS"'
    FILENAME == ARGV[1] { if (!($0 in want)) { want[$0] = 1; order[++n] = $0 }; next }
    ours($0) {
      if (($0 in want) && !($0 in seen)) { seen[$0] = 1; print > out } else { dropped++ }
      next
    }
    { print > out }
    END {
      for (i = 1; i <= n; i++) if (!(order[i] in seen)) { print order[i] > out; added++ }
      print dropped + 0, added + 0
    }' "$want" "$old") || {
    rm -f "$new"
    say "cannot read $CRONTAB"
    return 1
  }
  set -- $changes
  DROPPED=${1:-0}
  ADDED=${2:-0}
  if [ "$DROPPED" = 0 ] && [ "$ADDED" = 0 ]; then
    rm -f "$new"
    return 0
  fi
  # every line CronEdit did not write must be in the new file, the same and in the same order
  if ! awk -v tag="$TAG" "$AWK_OURS"'
    FILENAME == ARGV[1] { if (!ours($0)) a[++n] = $0; next }
    !ours($0) { if (++m > n || a[m] != $0) bad = 1 }
    END { exit (bad || m != n) }' "$old" "$new"; then
    rm -f "$new"
    say "the new crontab would change lines CronEdit did not write; $CRONTAB is left as it is"
    event 2 "the new crontab would change lines it did not write; /etc/config/crontab is left as it is"
    return 1
  fi
  [ "$old" = /dev/null ] || cat "$CRONTAB" >"$keep" || {
    rm -f "$new"
    return 1
  }
  # cat into the file, so its owner, mode and links stay
  if ! cat "$new" >"$CRONTAB"; then
    [ -f "$keep" ] && cat "$keep" >"$CRONTAB"
    rm -f "$new"
    say "cannot write $CRONTAB; it is restored"
    event 2 "cannot write /etc/config/crontab; it is restored"
    return 1
  fi
  rm -f "$new" "$keep"
  event 0 "/etc/config/crontab: $ADDED line(s) added, $DROPPED removed"
  echo "cronedit: /etc/config/crontab: $ADDED line(s) added, $DROPPED removed"
  reload
}

started() { [ -f "$STARTED" ]; }

do_sync() {
  want "$VAR/crontab.want" || die "cannot write $VAR/crontab.want"
  apply "$VAR/crontab.want"
  local rc=$?
  rm -f "$VAR/crontab.want"
  return $rc
}

do_cleanup() {
  : >"$VAR/crontab.want" || die "cannot write $VAR/crontab.want"
  apply "$VAR/crontab.want"
  local rc=$?
  rm -f "$VAR/crontab.want"
  return $rc
}

# after add or remove: in line at once while the package is started; otherwise at its next start
follow() {
  if started; then
    do_sync
  else
    echo "cronedit: $NAME is stopped; /etc/config/crontab gets the change at its next start"
  fi
}

# ── the commands ─────────────────────────────────────────────────────────────────────────────────────────────────

cmd_add() {
  local l new
  [ "$#" -eq 1 ] || die 'usage: cronedit add "<min> <hour> <day> <month> <weekday> <command>" (one quoted argument)'
  parse "$1" || die "not added: $ERR"
  case ${LINE_OUT#* * * * * } in
    /*) ;;
    *) say "note: cron runs the command with a short PATH; give programs by their full path (/bin/..., /share/...)" ;;
  esac
  new=$LINE_OUT
  lock
  if [ -f "$LINES" ]; then
    while IFS= read -r l || [ -n "$l" ]; do
      blank "$l" && continue
      parse "$l" || continue
      [ "$LINE_OUT" = "$new" ] && die "not added: the same line is there already"
    done <"$LINES"
  fi
  # a last line without its newline would take the new one onto its end
  if [ -s "$LINES" ] && [ -n "$(tail -c 1 "$LINES")" ]; then
    echo >>"$LINES" || die "cannot write $LINES"
  fi
  printf '%s\n' "$new" >>"$LINES" || die "cannot write $LINES"
  echo "cronedit: added: $new"
  follow
}

cmd_list() {
  local l n=0 state
  if started; then state=started; else state=stopped; fi
  echo "$NAME is $state; its lines ($LINES):"
  if [ -f "$LINES" ]; then
    while IFS= read -r l || [ -n "$l" ]; do
      blank "$l" && continue
      n=$((n + 1))
      if ! parse "$l"; then
        echo "$n  $l   [skipped: $ERR]"
      elif [ -f "$CRONTAB" ] && grep -qxF -e "$LINE_OUT $TAG" "$CRONTAB"; then
        echo "$n  $l"
      else
        echo "$n  $l   [not in /etc/config/crontab]"
      fi
    done <"$LINES"
  fi
  [ "$n" -gt 0 ] || echo "(none)"
}

cmd_remove() {
  local l n=0 hit= tmp
  [ "$#" -eq 1 ] || die "usage: cronedit remove <number> (the number cronedit list shows)"
  case $1 in '' | *[!0-9]* | 0) die "usage: cronedit remove <number> (the number cronedit list shows)" ;; esac
  lock
  [ -f "$LINES" ] || die "there is no line $1"
  tmp=$LINES.new
  : >"$tmp" || die "cannot write $tmp"
  while IFS= read -r l || [ -n "$l" ]; do
    blank "$l" && continue
    n=$((n + 1))
    if [ "$n" -eq "$1" ]; then
      hit=$l
      continue
    fi
    printf '%s\n' "$l" >>"$tmp" || {
      rm -f "$tmp"
      die "cannot write $tmp"
    }
  done <"$LINES"
  if [ -z "$hit" ]; then
    rm -f "$tmp"
    die "there is no line $1 (cronedit list shows $n)"
  fi
  mv -f "$tmp" "$LINES" || die "cannot write $LINES"
  echo "cronedit: removed: $hit"
  follow
}

cmd_check() {
  local bad old=$CRONTAB
  [ -f "$old" ] || old=/dev/null
  lock
  want "$VAR/crontab.want" 2>/dev/null || die "cannot write $VAR/crontab.want"
  bad=$(awk -v tag="$TAG" "$AWK_OURS"'
    FILENAME == ARGV[1] { want[$0] = 1; next }
    ours($0) { if (!($0 in want) || ($0 in seen)) bad = 1; seen[$0] = 1 }
    END { for (l in want) if (!(l in seen)) bad = 1; print bad + 0 }' "$VAR/crontab.want" "$old")
  rm -f "$VAR/crontab.want"
  [ "$bad" = 0 ]
}

[ "$(id -u)" = 0 ] || die "run it as admin (root): it writes /etc/config/crontab"

case ${1-} in
  add) shift && cmd_add "$@" ;;
  list | ls) cmd_list ;;
  remove | rm) shift && cmd_remove "$@" ;;
  sync) lock && do_sync ;;
  cleanup) lock && do_cleanup ;;
  check) cmd_check ;;
  *)
    cat <<'EOF'
usage: cronedit add "<min> <hour> <day> <month> <weekday> <command>"
       cronedit list
       cronedit remove <number>
EOF
    exit 1
    ;;
esac
