#!/usr/bin/env bash

# boot_to v0.0.1
# Copyright August 28, 2016, Francisco Gómez <espectalll@kydara.com>
# 
# 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, either version 3 of the License, or
# any later version.
# 
# 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.
# 
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

r=$(tput sgr0)
b=$(tput bold)
i=$(tput sitm)
red=$(tput setaf 1)
green=$(tput setaf 2)

error="${b}${red}ERROR:${r}"
usage="Usage: ${i}boot-to [--no-usb] windows|linux${r}"

if [[ -n $1 ]]; then
    if [ $EUID -eq 0 ]; then
        win=$(efibootmgr | grep Windows | cut -d* -f1 | tail -c 5)
        lin=$(efibootmgr | grep Linux | cut -d* -f1 | tail -c 5)
        if [ $1 = "--no-usb" ]; then
            shift
        else
            usb=$(efibootmgr | grep USB | cut -d* -f1 | tail -c 5)
        fi
        if [ $1 = "windows" ]; then
            efibootmgr -o ${usb/%/,}${win},${lin}
            exit $?
        elif [ $1 = "linux" ]; then
            efibootmgr -o ${usb/%/,}${lin},${win}
            exit $?
        else
            echo "${error} invalid arguments passed"
            echo $usage
            exit 64
        fi
    else
        echo "${error} superuser permissions required"
        exit 77
    fi
else
    echo "${error} no arguments passed"
    echo $usage
    exit 64
fi