#!/bin/bash

if [[ $EUID > 0 ]]; then
    if [[ $1 = "switch" ]] || [[ $1 = "default" ]]
        then echo "Please run as root"
        exit
    fi
fi

current=$(sed -n '3p' /etc/prime/config)
bootcard=$(sed -n '2p' /etc/prime/config)

if [[ $1 = "switch" ]]; then
    if [[ $2 = "intel" ]]; then
        if [[ $current = "I" ]]; then
            echo -e "\nIntel VGA already in use!!!\n"
        else
            echo -e "\nPlease logout to switch graphics\n"
            sed -i '1 c2' /etc/prime/config
            sleep 3 
        fi
    elif [[ $2 = "nvidia" ]]; then
        if [[ $current = "D" ]]; then
            echo -e "\nNvidia VGA already in use!!!\n"
        else
            echo -e "\nPlease logout to switch graphics\n"
            sed -i '1 c1' /etc/prime/config
            sleep 3 
        fi      
    else echo -e "\nUse: vga switch intel|nvidia\n"     
    fi

elif [[ $1 = "default" ]]; then
    if [[ $2 = "intel" ]]; then
        echo -e "\nBoot default: Intel\n"
        sed -i '2 cI' /etc/prime/config
    elif [[ $2 = "nvidia" ]]; then
        echo -e "\nBoot default: Nvidia\n"
        sed -i '2 cD' /etc/prime/config  
    elif [[ $2 = "keep" ]]; then
        sed -i '2 cL' /etc/prime/config   
        echo -e "\nBoot default: Latest Session\n"
    else echo -e "\nUse: vga default intel|nvidia|keep\n" 
    fi

elif [[ $1 = "query" ]]; then
    echo -e
    bash /usr/bin/prime-select.sh $1
        case "$bootcard" in
        I ) echo -e "\nDefault on boot: INTEL gpu\n";;
        D ) echo -e "\nDefault on boot: NVIDIA gpu\n";;
        L ) echo -e "\nDefault on boot: Last used\n";;
    esac
  
else
    echo -e "\nUSE: vga switch intel|nvidia         >    [ROOT] Hot Switch (logout required)\n"
    echo -e "\n     vga default intel|nvidia|keep   >    [ROOT] Set default VGA on boot (keep > remember latest session)\n"
    echo -e "\n     vga query                       >    Show current vga and boot settings"
fi
