#!/bin/sh
set -e

#
# Variables
#

# ESP
if command -v bootctl >/dev/null 2>&1 ; then
  ESP="$(bootctl --quiet --print-esp-path 2>/dev/null)"
fi

# Architecture
case "$(dpkg --print-architecture)" in
  amd64) EFI_ARCH="x64" ;;
  arm64) EFI_ARCH="aa64" ;;
  *) EFI_ARCH="none" ;;
esac


#
# Functions
#

# Compare MD5 sums of two files
compare_md5 () {
  local FILE SRC DST
  for FILE ; do [ -f "$FILE" ] || return 1 ; done
  SRC="$1" ; DST="$2"
  [ "$(md5sum < "$SRC")" = "$(md5sum < "$DST")" ] || return 1
}

# Update file from system to ESP if needed
update_file () {
  local SRC DST
  SRC="$1" ; DST="$2"
  if ( [ -f "$SRC" ] && ! compare_md5 "$SRC" "$DST" ) ; then
    printf "Installing '%s' to '%s'...\n" "$SRC" "$DST"
    install -p -D "$SRC" "$DST"
  fi
}

# Install Mok Manager to default path
install_mm () {
  [ -n "$ESP" ] || return
  [ "$EFI_ARCH" = "none" ] && return
  update_file "/usr/lib/shim/mm$EFI_ARCH.efi.signed" "$ESP/EFI/BOOT/mm$EFI_ARCH.efi"
}


#
# Main
#

case "$1" in
  configure)

    # On first install, create missing kernel files
    if [ -z "$2" ] ; then

      FILE="/etc/kernel/cmdline"
      if [ ! -f "$FILE" ] ; then
        printf "Creating '%s'...\n" "$FILE"
        sed 's/^BOOT_IMAGE=[^ ]* // ; s/ *systemd.machine_id=[^ ]*//' /proc/cmdline > "$FILE"
      fi

      FILE="/etc/kernel/tries"
      if [ ! -f "$FILE" ] ; then
        printf "Creating '%s'...\n" "$FILE"
        printf "2\n" > "$FILE"
      fi

    fi

    # Install Mok Manager to default path
    install_mm
  ;;

  triggered)
    install_mm
  ;;

  abort-upgrade|abort-remove|abort-deconfigure)
  ;;

  *)
    printf "postinst called with unknown argument '%s'\n" "$1" >&2
    exit 1
  ;;
esac

#DEBHELPER#

exit 0
