#!/bin/bash

__find_esp__() {
  local parttype
  local fstype
  local device

  while read -r device; do
    read -r parttype fstype ESP <<<"$(lsblk -o "PARTTYPE,FSTYPE,MOUNTPOINT" "$device" 2>/dev/null | awk 'NR==2')"

    [[ "${parttype,,}" != "c12a7328-f81f-11d2-ba4b-00a0c93ec93b" ]] && continue
    [[ "${fstype,,}" != "vfat" ]] && continue
    [[ -z $(findmnt -sn "$ESP") ]] && continue

  done <<<"$(fdisk -l 2>/dev/null | grep -i efi | cut -d " " -f 1)"

  if [ -z "${ESP}" ]; then
    ESP=$(grep -i "/efi" /etc/fstab | awk '{print $2}')
    if [ -z "${ESP}" ]; then
      ESP=$(grep -i "/boot" /etc/fstab | awk '{print $2}')
      if [ -z "${ESP}" ]; then
        ESP=$(bootctl --print-esp-path)
        if [ -z "${ESP}" ]; then
          exit 1
        fi
      fi
    fi
  fi

  echo "Found ${ESP}"
  readonly ESP
}

__has_esp__() {
  __find_esp__

  mount "$ESP" &>/dev/null
  [[ -d "$ESP/EFI" ]] && return 0 || return 1
}


THEME_NAME="melawy-nier-a2"

echo "Searching rEFInd installation in EFI partition..."
if ! __has_esp__; then
  echo "EFI partition not found" >&2
  exit 1
fi

REFIND_DIR=$(find "$ESP" -type d -iname refind)
if ! [[ -d "${REFIND_DIR}" ]]; then
  echo "rEFInd not installed in $ESP" >&2
  exit 1
fi
echo "Found rEFInd in ${REFIND_DIR}"

echo "Installing themes in ${REFIND_DIR}"

cp -vrf "/usr/share/refind/themes" "${REFIND_DIR}/"

REFIND_CONF_PATH="${REFIND_DIR}/refind.conf"

cp -vf "/etc/refind-menu-generator/refind.conf" "${REFIND_DIR}/refind.conf"

RESULT=$(grep "theme" "$REFIND_CONF_PATH")

if [[ "$?" = "0" ]]; then
  CURRENT_THEME=$(echo $RESULT | cut -d"/" -f2)
  if [[ "$?" == "0" ]]; then
    sed -e "s/$CURRENT_THEME/$THEME_NAME/g" -i "$REFIND_CONF_PATH"
  fi
else
  if [[ -z "$(tail -n 1 -c 1 $REFIND_CONF_PATH)" ]];then
    echo "include themes/$THEME_NAME/theme.conf" >> "$REFIND_CONF_PATH"
  else
    echo -e "\ninclude themes/$THEME_NAME/theme.conf" >> "$REFIND_CONF_PATH"
  fi
fi

echo "calamares yes" > /etc/refind-menu-generator/install_refind_theme.status
