#!/bin/sh
# Prepares the unpacked package before Package Center installs it: checks the answers of the wizard and that this NAS
# can run the Node.js inside the package, then writes the permissions DSM gives the package's user (conf/resource),
# the DSM shortcut and the settings. Everything is in the unpacked package ($SYNOPKG_PKGINST_TEMP_DIR, which becomes
# /var/packages/kumoyami/target). Exiting with an error cancels the installation and shows the message.
# On an upgrade (also from the Container Manager versions of the package, which saved the same settings) the answers
# of the install are read from the settings postinst saved.
# shellcheck disable=SC2154 # wizard_* come from WIZARD_UIFILES
. "$(dirname "$0")/common"

DEST="${SYNOPKG_PKGINST_TEMP_DIR:?run by Package Center}"
STATUS="${SYNOPKG_PKG_STATUS:-INSTALL}"

fail() {
  say "$1" "$2"
  exit 1
}

# Whatever stops this script without a reason (a command that crashed, a signal) still gets a message instead of
# DSM's generic «Error en la operación», with the step it was at; the details are in the package's log
STEP=answers
SAID=""
# shellcheck disable=SC2329 # run by the trap below
on_exit() {
  status=$?
  if [ "$status" -ne 0 ] && [ -z "$SAID" ]; then
    say "La instalación de KumoYami se ha detenido (paso: $STEP, código $status). Los detalles están en /var/log/packages/$PKG.log; envíanoslo desde kumoyami.com/docs." \
      "KumoYami's installation stopped (step: $STEP, code $status). The details are in /var/log/packages/$PKG.log; send it to us from kumoyami.com/docs."
  fi
}
trap on_exit EXIT
# A signal (Package Center giving up, a timeout) ends through exit, so that the EXIT trap runs in every sh
trap 'exit 129' HUP
trap 'exit 130' INT
trap 'exit 143' TERM
log "preinst $STATUS, version ${SYNOPKG_PKGVER:-?}, into $DEST"

# --- The answers ---
if [ "$STATUS" = UPGRADE ]; then
  saved=$(find_settings) ||
    fail "No se encuentran los ajustes de la instalación anterior. Desinstala KumoYami (tus datos se quedan en su carpeta compartida) e instálalo de nuevo con la misma carpeta de datos." \
      "The settings of the previous installation were not found. Uninstall KumoYami (your data stays in its shared folder) and install it again with the same data folder."
  log "settings of the installed version: $saved"
  DATA_SHARE=$(setting "$saved" DATA_SHARE)
  DATA_SUBFOLDER=$(setting "$saved" DATA_SUBFOLDER)
  MEDIA_SHARE=$(setting "$saved" MEDIA_SHARE)
  PORT=$(setting "$saved" PORT)
  TIMEZONE=$(setting "$saved" TIMEZONE)
  # The GPU box of the install; an install from before the box (0.1.7 or earlier) used the GPU
  GPU=$(setting "$saved" GPU)
else
  DATA_SHARE=$(trim "${wizard_data_share:-kumoyami}")
  DATA_SUBFOLDER=$(trim "${wizard_data_subfolder:-}" | sed 's#^/*##; s#/*$##')
  MEDIA_SHARE=$(trim "${wizard_media_share:-}")
  PORT=$(trim "${wizard_port:-4890}")
  TIMEZONE=$(trim "${wizard_timezone:-Europe/Madrid}")
  # «Usar la gráfica del NAS para convertir vídeo»: "true" or "false" (the armv8 package has no such box)
  GPU=yes
  [ "${wizard_gpu:-true}" = false ] && GPU=no
fi
[ "$GPU" = no ] || GPU=yes

# --- Checks (the wizard checks the same, but an upgrade or synopkg install from the command line skips it) ---
STEP=checks
valid_share "$DATA_SHARE" ||
  fail "El nombre de la carpeta compartida de los datos no es válido: «$DATA_SHARE»." \
    "The name of the shared folder for the data is not valid: \"$DATA_SHARE\"."
if [ -n "$DATA_SUBFOLDER" ]; then
  bad=""
  case "/$DATA_SUBFOLDER/" in */../* | */./*) bad=yes ;; esac
  printf '%s' "$DATA_SUBFOLDER" | grep -Eq '^[A-Za-z0-9 ._-]+(/[A-Za-z0-9 ._-]+)*$' || bad=yes
  if [ -n "$bad" ]; then
    fail "La subcarpeta de los datos no es válida: «$DATA_SUBFOLDER»." \
      "The data subfolder is not valid: \"$DATA_SUBFOLDER\"."
  fi
fi

printf '%s' "$PORT" | grep -Eq '^[0-9]{4,5}$' && [ "$PORT" -ge 1025 ] && [ "$PORT" -le 65535 ] ||
  fail "El puerto tiene que ser un número entre 1025 y 65535." "The port must be a number from 1025 to 65535."
case "$PORT" in
  5000 | 5001 | 5005 | 5006)
    fail "El puerto $PORT es de DSM: elige otro (por ejemplo 4890)." "Port $PORT belongs to DSM: choose another one (for example 4890)."
    ;;
esac
# On an upgrade the old version has been stopped already (and its container, for the Container Manager versions)
if [ "$STATUS" != UPGRADE ] && port_in_use "$PORT"; then
  fail "Algo de este NAS ya usa el puerto $PORT. Si es KumoYami en un proyecto de Container Manager, detén ese proyecto antes (tus datos siguen en su carpeta), o elige otro puerto." \
    "Something on this NAS already uses port $PORT. If it is KumoYami in a Container Manager project, stop that project first (its data stays in its folder), or choose another port."
fi

printf '%s' "$TIMEZONE" | grep -Eq '^(UTC|[A-Za-z]+(/[A-Za-z0-9_+-]+){1,2})$' ||
  fail "La zona horaria no es válida: «$TIMEZONE» (por ejemplo Europe/Madrid)." \
    "The time zone is not valid: \"$TIMEZONE\" (for example Europe/Madrid)."

# The shared folder with the owner's content (optional): it must exist, since the data-share worker would otherwise
# create an empty one with that name
[ "$MEDIA_SHARE" = "$DATA_SHARE" ] && MEDIA_SHARE=""
if [ -n "$MEDIA_SHARE" ]; then
  valid_share "$MEDIA_SHARE" ||
    fail "El nombre de la carpeta compartida con tu contenido no es válido: «$MEDIA_SHARE»." \
      "The name of the shared folder with your content is not valid: \"$MEDIA_SHARE\"."
  if [ "$STATUS" != UPGRADE ]; then
    share_path "$MEDIA_SHARE" > /dev/null ||
      fail "No existe la carpeta compartida «$MEDIA_SHARE». Escribe el nombre tal como aparece en File Station, o déjalo vacío." \
        "There is no shared folder \"$MEDIA_SHARE\". Type the name as File Station shows it, or leave it empty."
  elif ! share_path "$MEDIA_SHARE" > /dev/null; then
    # Deleted since the install: not asked for again
    log "the content shared folder $MEDIA_SHARE no longer exists: left out"
    MEDIA_SHARE=""
  fi
fi

# --- This NAS runs the package's Node.js: an official linux build, which needs glibc 2.28 (DSM 7.2 has 2.36) and this
# processor's architecture. Checked now so that an unsupported NAS stops here with the reason, not at the first start.
STEP=runtime
node_check=$("$DEST/node/bin/node" -e 'console.log(process.version + " " + process.arch)' 2>&1) ||
  fail "Este NAS no puede ejecutar KumoYami Server (hace falta DSM 7.2 o posterior y un procesador $(uname -m) compatible): $node_check" \
    "This NAS cannot run KumoYami Server (it needs DSM 7.2 or later and a compatible $(uname -m) processor): $node_check"
log "node: $node_check; $(ldd --version 2>&1 | head -n 1)"

# --- What DSM gives the package's user: conf/resource ---
# The data-share worker gives the package's user read/write on the data shared folder and, when the wizard names one,
# read-only on the shared folder with the content; video-driver adds it to the group of /dev/dri. The data folder's
# name is written in (the resource ships it as {{wizard_data_share}}, which an upgrade has no wizard to fill), and the
# content folder's entry is added with its name rather than shipped as {{wizard_media_share}}: an empty name is not a
# shared folder. With the wizard's GPU box unticked, video-driver is taken out: DSM never gives the package's user the
# GPU's group, and the app converts with the processor (start-stop-status). The resource is in the unpacked package next to these scripts, before DSM moves it to
# /var/packages/kumoyami/conf; the workers read it when the package is enabled, after postinst. If it cannot be
# changed, the owner gives the permission in DSM.
STEP=resource
resource=""
for f in "$(dirname "$DEST")/conf/resource" "$(dirname "$0")/../conf/resource"; do
  if [ -f "$f" ]; then
    resource="$f"
    break
  fi
done
if [ -n "$resource" ] && grep -q '"shares": \[' "$resource"; then
  entry=""
  [ -n "$MEDIA_SHARE" ] && entry="      { \"name\": \"$MEDIA_SHARE\", \"permission\": { \"ro\": [\"$PKG\"] } },"
  # Each line is held until the next one, so that dropping video-driver can take the comma off the line before it
  if awk -v entry="$entry" -v share="$DATA_SHARE" -v gpu="$GPU" '
      function out(line) { if (held) print last; last = line; held = 1 }
      gpu == "no" && /"video-driver"/ { sub(/,[ \t]*$/, "", last); next }
      { gsub(/\{\{wizard_data_share\}\}/, share); out($0) }
      /"shares": \[/ && !done && entry != "" { out(entry); done = 1 }
      END { if (held) print last }
    ' "$resource" | replace_file "$resource"; then
    log_file "conf/resource ($resource)" "$resource"
  else
    log "conf/resource $resource could not be written; the owner gives the permissions in DSM"
  fi
else
  log "conf/resource not found next to the package"
fi

# The port of the DSM main menu shortcut and Package Center's «Open» (ui/config): the launcher's; not worth stopping for
if [ -f "$DEST/ui/config" ]; then
  sed "s/\"port\": \"[0-9]*\"/\"port\": \"$PORT\"/" "$DEST/ui/config" | replace_file "$DEST/ui/config" ||
    log "ui/config: the port could not be set"
fi
# The ports DSM's firewall lists for KumoYami (kumoyami.sc, port-config, read after postinst): the launcher's and the
# two the app opens after it, the Biblioteca's and Archivos' (server.js: PORT + 1 and PORT + 2)
if [ -f "$DEST/kumoyami.sc" ]; then
  sed "s#^dst.ports=.*#dst.ports=\"$PORT,$((PORT + 1)),$((PORT + 2))/tcp\"#" "$DEST/kumoyami.sc" |
    replace_file "$DEST/kumoyami.sc" || log "kumoyami.sc: the ports could not be set"
fi

# --- The settings, for postinst (which keeps them in the package's var folder), start-stop-status and the next
# upgrade. GPU is the install wizard's GPU box (yes or no), kept across upgrades. HW, the GPU box of some Container
# Manager builds, is not carried over: it was about the container, and the native package tries the GPU unless GPU
# says no, falling back to the processor. ---
STEP=settings
(
  umask 077
  {
    echo "DATA_SHARE='$DATA_SHARE'"
    echo "DATA_SUBFOLDER='$DATA_SUBFOLDER'"
    echo "MEDIA_SHARE='$MEDIA_SHARE'"
    echo "PORT='$PORT'"
    echo "TIMEZONE='$TIMEZONE'"
    echo "GPU='$GPU'"
  } > "$DEST/$SETTINGS_NAME"
) || fail "No se puede escribir en $DEST." "Cannot write to $DEST."
log "settings: data $DATA_SHARE${DATA_SUBFOLDER:+/$DATA_SUBFOLDER}, content ${MEDIA_SHARE:-none}, port $PORT, $TIMEZONE, GPU $GPU"
exit 0
