#!/bin/bash

if [[ "$UID" != 0 ]]; then
    echo "USER NOT ROOT"
    sudo $0
    exit
else
    echo "USER IS ROOT"
fi

PWD=$(dirname $0)

ESP_PATH=$(bootctl --print-esp-path)
REFIND_CONF_PATH="${ESP_PATH}/EFI/refind/refind.conf"
THEME_PATH="${ESP_PATH}/EFI/refind/themes"

if [[ ! -d "$THEME_PATH" ]];then
    mkdir -p "$THEME_PATH"
fi

THEME_NAME="melawy-nier-a2"

cp -vrf --remove-destination --no-dereference --preserve=links "$PWD/$THEME_NAME" "$THEME_PATH/"

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
