#!/bin/bash

# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; version 3 of the License.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.

# This program is optimized for Manjaro OS

url=https://www.rodsbooks.com/refind/configfile.html
refind_efi_path=/boot/efi/EFI/refind/refind.conf
conf=$(mktemp)

gui() {
    local icon=/usr/share/icons/manjaro/maia/maia.svg
    local window_icon=/usr/share/icons/manjaro/maia/32x32.png
    
    if [ -r "$icon" ] ; then
        GDK_BACKEND=x11 /usr/bin/yad --center --window-icon="$icon" --image="$window_icon" --title="Manjaro Refind Installer" "$@"
    else
        GDK_BACKEND=x11 /usr/bin/yad --center --title="Manjaro Refind Installer" "$@"
    fi
}

txt_editor() {
     txt_ed=$(gui --image=info --image-on-top --text="Write your text editor" --entry)
}

# Welcome
gui --text="\n\n<b>Welcome to Refind boot loader installer.</b>

If you only have one kernel you have finished 
otherwise select in the next step the default 
kernel to use." --button=_Cancel:1 --button=_OK:0
[[ $? == 1 ]] && exit 1

############################
# Check installed kernel
inst_kernel=($(mhwd-kernel -li | grep "*" | awk '{print $2}' | tr '\n' ' '))

# Set kernel to use with refind and set it
num_kern=$(echo "${inst_kernel[@]}" | wc -w)

if [[ $num_kern -ge 2 ]]; then
    kern=$(gui --entry \
    --button="Select" \
    --text "Please choose default kernel to use:" \
    --entry-text \
    "${inst_kernel[@]}")
    def_kern=$(echo "${kern:5}" | sed 's/./& /')
    default-kernel $def_kern > /dev/null 2>&1
else
    refind-install > /dev/null 2>&1
fi

# make linux graphic by default
sed -i 's/#use_graphics_for osx,linux/use_graphics_for linux/' $refind_efi_path


# make boot time to 10
sed -i 's/timeout 20/timeout 10/' $refind_efi_path

while true; do
# manage refind config
cat $refind_efi_path > $conf

# last check
gui --text="\n\nWell done rEFInd boot manager is installed and 
<b>kernel $def_kern</b> is set to default.

Now you can set optional settings in <b>refind.conf</b> file
like timeout for boot or set the default OS to start.

Select in the next step if open the man page, the settings or exit" \
    --button="Finish":0 --button="Man Page":1 --button="Settings":2
    opt=$?
    case $opt in 
        0) exit 0 ;;
        1) sudo -u $(logname) xdg-open $url ;;
        2) txt_ed=$(gui --text="Write your text editor\n(enter to continue)" --no-buttons --entry) ; $txt_ed $conf ; cp -f $conf $refind_efi_path ;;
    esac
done

# Done