# Shared by the scripts of the native package. DSM 7 runs them as the package's own user ("kumoyami", conf/privilege),
# never as root (https://help.synology.com/developer-guide/privilege/privilege_config.html). What needs root is done by
# DSM's resource workers (conf/resource): data-share creates the data shared folder and gives the package's user
# read/write on it, video-driver adds the package's user to the group "videodriver", which owns /dev/dri.
# shellcheck shell=sh disable=SC2034 # the variables are used by the scripts that source this file

PKG="${SYNOPKG_PKGNAME:-kumoyami}"
# The package's own folder (/var/packages/kumoyami/var, kept across upgrades): settings, pid file, caches of fontconfig
PKGVAR="${SYNOPKG_PKGVAR:-/var/packages/$PKG/var}"
SETTINGS_NAME=settings.conf
# Written next to the settings the first time the package starts (start-stop-status): only then may postuninst delete
# the data
RAN_NAME=ran

# A message for the person installing, in their DSM language: Spanish for Spanish, English otherwise
# (https://help.synology.com/developer-guide/synology_package/show_massage.html). Package Center shows it as HTML, so
# messages never hold < or >. SAID tells preinst's exit trap that the reason was given.
say() {
  SAID=1
  if [ "${SYNOPKG_DSM_LANGUAGE:-}" = spn ]; then msg="$1"; else msg="$2"; fi
  log "$msg"
  if [ -n "${SYNOPKG_TEMP_LOGFILE:-}" ]; then
    printf '%s\n' "$msg" >> "$SYNOPKG_TEMP_LOGFILE"
  else
    printf '%s\n' "$msg" >&2
  fi
}

# Lines on stderr go to the package's log, /var/log/packages/kumoyami.log (DSM 7)
log() { printf '%s %s\n' "$(date '+%Y-%m-%d %H:%M:%S')" "$*" >&2; }

# Is something listening on this TCP port? /proc/net/tcp and tcp6 list the sockets with their port in hex, and the
# state 0A is LISTEN (proc(5)). Works as any user, unlike netstat -p.
port_in_use() {
  hex=$(printf '%04X' "$1")
  awk -v p=":$hex" 'substr($2, length($2) - 4) == p && $4 == "0A" { found = 1 } END { exit !found }' \
    /proc/net/tcp /proc/net/tcp6 2>/dev/null
}

# The settings chosen in the install wizard, saved by postinst for the next upgrade (the Container Manager versions of
# the package saved the same file). While a new version's preinst runs, /var/packages/kumoyami/var is not always
# linked yet, so its volume folder (@appdata) is tried too.
find_settings() {
  for f in "$PKGVAR/$SETTINGS_NAME" "/var/packages/$PKG/var/$SETTINGS_NAME" \
    "${SYNOPKG_PKGDEST_VOL:-/volume1}/@appdata/$PKG/$SETTINGS_NAME" /volume*/@appdata/"$PKG"/"$SETTINGS_NAME"; do
    if [ -r "$f" ]; then
      echo "$f"
      return 0
    fi
  done
  return 1
}

# A value of a settings file (KEY='value' lines, written by preinst)
setting() {
  sed -n "s/^$2='\\(.*\\)'\$/\\1/p" "$1" | head -n 1
}

# The folder of a shared folder, whichever volume it is on: the link DSM makes for the shares of the package
# (/var/packages/kumoyami/shares/<name>, since DSM 7.0-41201), or /volumeN/<name>
share_path() {
  link="/var/packages/$PKG/shares/$1"
  if [ -e "$link" ]; then
    (cd "$link" 2>/dev/null && pwd -P) && return 0
  fi
  for v in /volume*; do
    case "$v" in */@*) continue ;; esac
    if [ -d "$v/$1" ]; then
      echo "$v/$1"
      return 0
    fi
  done
  return 1
}

# The NAS's volumes: data volumes (/volume1, /volume2…) and the USB and eSATA disks mounted now (/volumeUSB1,
# /volumeSATA1). The app's folder picker starts at each of them (SYNOLOGY_VOLUMES). With no container in between, a
# disk that is unplugged later only makes its folders unreadable.
nas_volumes() {
  for v in /volume[0-9]* /volumeUSB[0-9]* /volumeSATA[0-9]*; do
    case "${v#/}" in *[!a-zA-Z0-9]*) continue ;; esac
    [ -d "$v" ] && echo "$v"
  done
}

# The shared folders of those volumes, one path per line: the folders at the top of each, but DSM's own (@appstore,
# #snapshot…) and encrypted ones that are locked (only their @name@ folder is there)
nas_shares() {
  for v in $(nas_volumes); do
    for d in "$v"/*; do
      [ -d "$d" ] || continue
      name=${d##*/}
      case "$name" in @* | \#* | .* | lost+found) continue ;; esac
      [ -e "$v/@$name@" ] && continue
      printf '%s\n' "$d"
    done
  done
}

# A file, line by line, into the package's log
log_file() {
  log "$1:"
  sed 's/^/    | /' "$2" >&2
}

# Writes stdin to a file of the unpacked package through a new file and a rename: the files DSM unpacked may belong to
# root, but their folder is the package user's, and a rename replaces a file whatever its owner
replace_file() {
  cat > "$1.new" && mv -f "$1.new" "$1"
}

# Share names as DSM allows them (also checked by the wizard)
valid_share() {
  printf '%s' "$1" | grep -Eq '^[A-Za-z0-9][A-Za-z0-9 ._-]{0,31}$'
}

trim() {
  printf '%s' "$1" | sed 's/^[[:space:]]*//; s/[[:space:]]*$//'
}
