#!/bin/bash

function dlgYN() {
    tput sc
    tput setaf 4
    printf "$1 (y/n)? "
    while :
    do
        read -n 1 -p "" YNQuestionAnswer
        if [[ $YNQuestionAnswer == "y" ]]; then
            tput rc; tput el
            tput sc
            eval $2=1 # Set parameter 2 of input to the return value
            break
        elif [[ $YNQuestionAnswer == "n" ]]; then
            tput rc; tput el
            printf ". $1?: \e[0;31mNo\e[0m\n"
            eval $2=0 # Set parameter 2 of input to the return value
            break
        fi
    done
}

function die() {
    tput setaf 1
    echo "$1"
    tput sgr0
    exit 1
}

if [ -z $1 ]; then
    tput setaf 1
    echo "You need to provide a file";
    tput sgr0
    exit 1
fi

tput setaf 1
if [[ $1 == *.java ]]; then
    echo "WARN: You probably didn't mean to end the filename with \".java\"."
fi

if [[ $1 == *.class ]]; then
    echo "WARN: You probably didn't mean to end the filename with \".class\"."
fi
tput sgr0


tput setaf 4
echo "> javac $1.java "
tput sgr0

javac "$1.java" || die "Error while trying to compile."


dlgYN "Run \"$1\"?" res
if [ $res -eq 1 ]; then
    tput setaf 4
    echo "> java $1"
    tput sgr0

    java $1 || die "Error while trying to run program."
fi
