#!/bin/sh
# Re-applies synoinfo.conf tweaks that DSM upgrades revert. Docs: Infra/syno.md.
#   synoinfo-hacks.sh          check + fix (systemd unit, early boot)
#   synoinfo-hacks.sh install  (Task Scheduler boot-up task "synoinfo hacks",
#     runs the master copy in /volume1/@scripts) reinstalls this script in
#     /usr/local/bin + the unit if an upgrade wiped them, then check + fix.
# The unit runs after the post-upgrade config merge (configupdate-rootfs) and
# before the pool and its SSD cache are assembled (syno-space), so no extra
# reboot. If the boot task still has something to fix, the early hook missed:
# it exits 1, the task mails the output ("notify on error"), reboot the NAS.
PATH=$PATH:/usr/syno/bin:/usr/syno/sbin
BIN=/usr/local/bin/synoinfo-hacks.sh
UNIT=/etc/systemd/system/synoinfo-hacks.service
# The journal is volatile and starts after this unit: log to a file.
LOG=/var/log/synoinfo-hacks.log
changed=""

set_key() { # file key value; hex values compare numerically (0x00 = 0x0)
  cur=$(get_key_value "$1" "$2")
  case "$3" in
    0x*) [ -n "$cur" ] && [ $((cur)) -eq $(($3)) ] && return ;;
    *) [ "$cur" = "$3" ] && return ;;
  esac
  synosetkeyvalue "$1" "$2" "$3" && changed="$changed $2=$3@$1"
}

install_hook() {
  cmp -s "$0" "$BIN" || install -m 700 "$0" "$BIN"
  cat > "$UNIT.new" <<'UNIT'
[Unit]
Description=Re-apply synoinfo.conf tweaks before the storage pool (Infra/syno.md)
DefaultDependencies=no
After=local-fs.target configupdate-rootfs.service synocheckinfo.service
Before=syno-space.service syno-space.target

[Service]
Type=oneshot
RemainAfterExit=yes
ExecStart=/usr/local/bin/synoinfo-hacks.sh

[Install]
WantedBy=syno-space.target
UNIT
  if cmp -s "$UNIT.new" "$UNIT"; then rm "$UNIT.new"; return; fi
  mv "$UNIT.new" "$UNIT"
  systemctl daemon-reload && systemctl enable synoinfo-hacks.service
  echo "(Re)installed $UNIT"
}

[ "$1" = install ] && install_hook

for f in /etc.defaults/synoinfo.conf /etc/synoinfo.conf; do
  # eSATA port (bit 0x4, the Samsung SSD read cache) seen as an internal disk.
  set_key "$f" esataportcfg 0x0
  # Immutable (WORM) snapshots, hidden on this model: crbo-backup uses them.
  set_key "$f" support_worm yes
  cur=$(get_key_value "$f" internalportcfg)
  set_key "$f" internalportcfg "$(printf '0x%x' $(( ${cur:-0x3} | 0x4 )))"
done

msg="${1:-boot hook}: ${changed:+re-applied:}${changed:-all keys already set}"
echo "$(date "+%F %T") $msg" >> "$LOG"
logger -t synoinfo-hacks "$msg"
[ -z "$changed" ] && exit 0
[ "$1" = install ] || exit 0
echo "Re-applied by the boot task, the early hook missed:$changed"
echo "Reboot the NAS to bring the SSD cache back."
exit 1
