# Super Grub Disk - tools.cfg
# Copyright (C) 2009,2010,2011,2012,2013,2014,2015  Adrian Gibanel Lopez.
#
# Super Grub Disk 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, either version 3 of the License, or
# (at your option) any later version.
#
# Super Grub Disk 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.
#
# You should have received a copy of the GNU General Public License
# along with Super Grub Disk.  If not, see <http://www.gnu.org/licenses/>.

# This script contains several helper functions used in other cfg files .

# Modified by	: Nguyen Tu.
# Website		: https://www.aioboot.com.
# Last modified	: 05.03.2018.

function strcontains {
	set str="$1"
	set pattern="$2"
	if regexp ".*${pattern}.*" "$str"; then
		return 0;
	else
		return 1;
	fi
}

# Function: withplatform
# Return 0 (true) if our grub platform is sufficient for the argument
# Return 1 (false) if our grub platform is not sufficient
#
# argument is just efi or anything else for now
# echo out a failure message with a sleep when the check fails
# NOTE only checks we are efi if we want it and are not efi if we don't
function withplatform {
	if [ "${1}" = "efi" ]; then
		if [ "${grub_platform}" != "efi" ]; then
			sgdwpwant="UEFI"
			sgdwphave="BIOS"
		else
			return 0
		fi
	else
		if [ "${grub_platform}" = "efi" ]; then
			sgdwpwant=$"BIOS Compatibility Mode"
			sgdwphave="UEFI"
		else
			return 0
		fi
	fi
	echo $"Sorry, but we are booted via ""${sgdwphave}"$" and can not load this OS."
	echo $"Please try booting SG2D via"" ${sgdwpwant}."
	echo $"Press escape to return to the menu"
	sleep --interruptible 9999
	return 1
}

# Function: searchindevice
# According to global variables
# Return 0 (true) if the device should be searched for OS / cfgs / etc.
# Return 1 (false) if it should not be searched
#
# Device should be entered without ()
# Input example: fd0
#
# TODO: To be simplified when test function is fixed in upstream GRUB2
function searchindevice {
	if [ -z "$3" ]; then fd0search="$3"; else fd0search="off"; fi
	if [ -z "$2" ]; then cdsearch="$2"; else cdsearch="off"; fi
	
    set device="$1"

    if strcontains "$device" "fd" ; then
		fdcontains="yes"
    else
		fdcontains="no"
    fi

    if strcontains "$device" "cd" ; then
		cdcontains="yes"
    else
		cdcontains="no"
    fi

    if [ "$fdcontains" != "yes" -a "$cdcontains" != "yes" ]	\
    -o	\
    [ "$fdcontains" = "yes"  -a  "$fd0search" = "on" ]	\
    -o	\
    [ "$cdcontains" = "yes"  -a  "$cdsearch" = "on" ]	\
    ; then
		return 0;
    else
		return 1;
    fi
}
