#!/bin/bash

showExample() { 
    echo -e "\ne.g. \""$(basename -- "$0")" eDP1 1920 1080 60\"\n"
}

createRes() {
    cvt "$WIDTH" "$HEIGHT" "$REFRESH" | grep Modeline | sed "s/Modeline//" | xargs xrandr --newmode
}

addRes() {
    xrandr --addmode "$DEVICE" "$WIDTH"x"$HEIGHT"_"$REFRESH".00
}

switchRes() {

    while true; do
        read -p "$1" yn
        case $yn in
            [Yy]* ) xrandr --output "$DEVICE" --mode "$WIDTH"x"$HEIGHT"_"$REFRESH".00 || {
                        echo -e "\nERROR switching resolution with \"xrandr\"\n"
                        return 1
                    }; break;;
            [Nn]* ) break;;
            * ) echo "Please type \"y\" or \"n\"";;
        esac
    done
}

switchResAnyway() {
    switchRes "Adding resolution failed. Try to switch to this resolution anyway? (y/n) "
}

switchResNow() {
    switchRes "Switch to this resolution now? (y/n) "
}

# check arguments
if [ -z "$1" ]; then
    echo "Please provide an output devide as the first argument"
    showExample
    exit 128
fi

if [ -z "$2" ]; then
    echo "Please provide a screen width as the second argument"
    showExample
    exit 128
fi

if [ -z "$3" ]; then
    echo "Please provide a screen height as the third argument"
    showExample
    exit 128
fi

if [ -z "$4" ]; then
    echo "Please provide a refresh rate as the fourth argument"
    showExample
    exit 128
fi

#init
DEVICE=$1
WIDTH=$2
HEIGHT=$3
REFRESH=$4

createRes || {
    echo -e "\nERROR creating resolution with \"cvt\"\n"
    switchResAnyway
    exit 1
}

addRes || {
    echo -e "\nERROR adding resolution with \"xrandr\"\n"
    switchResAnyway
    exit 1
}

switchResNow
exit 0