#!/bin/bash

function check_root {
  [ $EUID -eq 0 ] && return
  echo "refind-menu-generator requires root privileges to work" >&2
  exit 1
}

check_root

__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
}

# Copied from https://raw.githubusercontent.com/jaltuna/refind-theme-nord/main/setup.sh
# Verify EFI System Partition
__has_esp__() {
  __find_esp__

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

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}"


if [ -z "${ESP}" ]; then
  exit 1
else

  if [ ! -d "${ESP}/EFI/Linux" ]; then
    mkdir -p "${ESP}/EFI/Linux"
    if [ -d "${ESP}/EFI/linux" ]; then
      KERNEL_DIR="${ESP}/EFI/linux"
    fi
  else
    KERNEL_DIR="${ESP}/EFI/Linux"
  fi

fi

echo "Found $KERNEL_DIR"

#theme=$(grep "themes" "/efi/EFI/refind/refind.conf" | cut -d"/" -f2)

theme=$(cat "/etc/refind-menu-generator/theme.conf" | awk '{$1=$1;print}')

if [ -d "$KERNEL_DIR" ]; then

    if [ -f "${ESP}/EFI/Linux/cmdline.txt" ]; then
        cmdline=$(sed -e 's/^[[:space:]]//g' -e 's/[[:space:]]$//g' "${ESP}/EFI/Linux/cmdline.txt")

    elif [ -f "/etc/kernel/cmdline" ]; then
        cmdline=$(sed -e 's/^[[:space:]]//g' -e 's/[[:space:]]$//g' "/etc/kernel/cmdline")

    elif [ -f "/boot/refind_linux.conf" ]; then
        cmdline=$(head -n 1 < "/boot/refind_linux.conf" | sed -e 's|"Boot with standard options"||g' | awk '{$1=$1;print}' | sed -e 's/"//g')

    elif [ -f "/efi/refind_linux.conf" ]; then
        cmdline=$(head -n 1 < "/efi/refind_linux.conf" | sed -e 's|"Boot with standard options"||g' | awk '{$1=$1;print}' | sed -e 's/"//g')

    elif [ -f "/boot/efi/refind_linux.conf" ]; then
        cmdline=$(head -n 1 < "/boot/efi/refind_linux.conf" | sed -e 's|"Boot with standard options"||g' | awk '{$1=$1;print}' | sed -e 's/"//g')

    else
        cmdline=$(sed -e 's/^[[:space:]]//g' -e 's/[[:space:]]$//g' -e 's/initrd.*$//g' "/proc/cmdline")
    fi

    cmdline_terminal="$cmdline systemd.unit=multi-user.target"

    echo "$cmdline"

    manual_conf=$(mktemp)


    template_choice=$(cat "/etc/refind-menu-generator/menu-template.conf" | awk '{$1=$1;print}')

    if [ ! -f "/etc/refind-menu-generator/${template_choice}.txt" ] || [ "$(ls -l /etc/refind-menu-generator/${template_choice}.txt | awk '{print $5}')" -lt 10 ]; then
      template="/etc/refind-menu-generator/menu-template.txt"
    else
      template="/etc/refind-menu-generator/${template_choice}.txt"
    fi


    kernels_list=$(ls -1 "${ESP}/EFI/Linux/" | grep 'linu' | grep -v 'fallback' | grep '\.efi$')

    for i in $kernels_list;
    do
        kernel=$(echo "$i" | sed 's/\.efi//g')
        kernel_efi=$kernel
        kernel_vmlinuz="vmlinuz-$kernel"

        osname=$(grep "^NAME=" /etc/os-release | cut -d'=' -f2 | sed -e 's/"//g')
        icon=$(grep "^ID=" /etc/os-release | cut -d'=' -f2 | sed -e 's/"//g')

        initramfs_tpl=$(echo "initramfs-$kernel" | sed "s/vmlinuz-//g")
        initramfs="$initramfs_tpl"

        echo "OSNAME: $osname; THEME: $theme; ICON: $icon; KERNEL: $kernel; KERNEL_EFI: $kernel_efi; KERNEL_VMLINUZ: $kernel_vmlinuz; INITRAMFS: $initramfs; CMDLINE: $cmdline"
        sed -e "s|{OSNAME}|$osname|g" -e "s|{THEME}|$theme|g" -e "s|{ICON}|$icon|g" -e "s|{KERNEL}|$kernel|g" -e "s|{KERNEL_EFI}|$kernel_efi|g" -e "s|{KERNEL_VMLINUZ}|$kernel_vmlinuz|g" -e "s|{INITRAMFS}|$initramfs|g" -e "s|{CMDLINE}|$cmdline|g" -e "s|{CMDLINE_TERMINAL}|$cmdline_terminal|g" "$template" >> "$manual_conf"
    done

    manual_end_conf=$(mktemp)

    template_end="/etc/refind-menu-generator/menu-end.txt"

    sed  -e "s/{THEME}/$theme/g" "$template_end" >> "$manual_end_conf"

    cat "$manual_end_conf" >> "$manual_conf"

    cp -vf "$manual_conf" "${ESP}/EFI/refind/manual.conf"

    if [ -d "${ESP}/EFI/boot" ]; then
      cp -vf "$manual_conf" "${ESP}/EFI/boot/manual.conf"
    fi

    rm -f "$manual_conf"
    rm -f "$manual_end_conf"
fi