#!/bin/bash

YKFDE_CONFIG_FILE="/etc/ykfde.conf"
YKFDE_NFC=""

build() {
  # shellcheck source=../ykfde.conf
  . "$YKFDE_CONFIG_FILE" || {
    ykfde_err 001 "Failed to read the YKFDE configuration file '$YKFDE_CONFIG_FILE'"
    exit 1
  }

  local mod

  add_module "dm-crypt"
  add_module "dm-integrity"
  if [[ "$CRYPTO_MODULES" ]]; then
    for mod in $CRYPTO_MODULES; do
      add_module "$mod"
    done
  else
    add_all_modules "/crypto/"
  fi

  add_binary "cryptsetup"
  add_binary "dmsetup"
  add_file "/usr/lib/udev/rules.d/10-dm.rules"
  add_file "/usr/lib/udev/rules.d/13-dm-disk.rules"
  add_file "/usr/lib/udev/rules.d/95-dm-notify.rules"
  add_file "/usr/lib/initcpio/udev/11-dm-initramfs.rules" "/usr/lib/udev/rules.d/11-dm-initramfs.rules"

  # cryptsetup calls pthread_create(), which dlopen()s libgcc_s.so.1
  add_binary "/usr/lib/libgcc_s.so.1"

  add_binary "tr"
  add_binary "ykchalresp"
  add_binary "ykinfo"
  add_binary "date"
  add_binary "sleep"
  add_binary "printf"
  add_file "/etc/ykfde.conf" "/etc/ykfde.conf"
  add_file "/usr/lib/ykfde-suspend/initramfs-suspend" "/ykfde-suspend" 755

  # nfc support
  if [ "$YKFDE_NFC" ]; then
    # serial drivers for nfc
    add_all_modules "/drivers/tty/serial/"
    add_all_modules "/drivers/usb/serial/"

    # nfc challenge response
    if [ -f "/etc/nfc/libnfc.conf" ]; then
      add_file "/etc/nfc/libnfc.conf"
    fi
    add_binary "ykchalresp-nfc" || {
      ykfde_err 001 "Failed to find ykchalresp-nfc (available from AUR)"
      exit 1
    }
  fi

  # plymouth support
  if [ -f "/usr/lib/plymouth/label.so" ]; then add_binary "/usr/lib/plymouth/label.so"; fi
  if [ -f "/usr/share/fonts/TTF/DejaVuSans.ttf" ]; then add_file "/usr/share/fonts/TTF/DejaVuSans.ttf"; fi
  if [ -f "/etc/fonts/fonts.conf" ]; then add_file "/etc/fonts/fonts.conf"; fi
  if [ -f "/etc/fonts/conf.d/60-latin.conf" ]; then add_file "/etc/fonts/conf.d/60-latin.conf"; fi

  add_runscript
}

ykfde_err() {
  local _rc
  _rc="$?"
  local code
  code="$1"
  local msg
  msg="$2"
  [ "$msg" ] && msg="ERROR $code [rc=$_rc]: $msg" || msg="ERROR $code [rc=$_rc]"
  printf '\n%s\n\n' "$msg" #exit 1;
}

help() {
  cat <<HELPEOF
This allows decrypting a custom device.
HELPEOF
}
