#!/usr/bin/env bash

set -e -u -o pipefail

echo

if [ $# -lt 1 ]
then
    echo '[ ERROR ]'
    echo '[ ERROR ] Hey! You forgot to give a name of your program!'
    echo '[ ERROR ]'
    echo '[ ERROR ] Run this command again but do it like this:'
    echo '[ ERROR ]'
    echo "[ ERROR ]     bash $0 'name of program.cpp'"
    echo '[ ERROR ]'
    exit 1
fi

found_files="$*"

echo "[ INFO ] User asked me to use '$found_files', let me check it..."

if [ -f "${found_files}" ]
then
    :
else
    if [ -f "${found_files}.c" ]
    then
        found_files="${found_files}.c"
    else
        if [ -f "${found_files}.cpp" ]
        then
            found_files="${found_files}.cpp"
        else
            echo '[ ERROR ]'
            echo '[ ERROR ] Hey! You wrote the filename with a typo!'
            echo '[ ERROR ]'
            echo '[ ERROR ] Fix a typo and run this command again with a correct name:'
            echo '[ ERROR ]'
            echo "[ ERROR ]     bash $0  'correct name of program.cpp'"
            echo '[ ERROR ]'
            exit 1
        fi
    fi
fi

echo "[ INFO ] I found file named '$found_files'."

extension_without_dot="$(
    echo "$found_files" | rev | tr '.' '\n' | head -n 1

)"

if [ "$extension_without_dot" = 'c' ]
then
    echo '[ INFO ] This file ends with .'"$extension_without_dot"' so I think it is written in C'
    L='C'
else
    echo '[ INFO ] This file ends with .'"$extension_without_dot"' so I think it is written in C++'
    L='C++'
fi

echo '[ INFO ] Let me try to compile this file...'

export UBSAN_OPTIONS=print_stacktrace=1
export TSAN_OPTIONS=halt_on_error=1

if [ "$L" = 'C' ]
then
    gcc -std=c11 -g -fsanitize=address,undefined -fno-sanitize-recover=all -Ofast "$found_files" -o ./a.out
else    
    g++ -std=c++11 -g -fsanitize=address,undefined -fno-sanitize-recover=all -Ofast "$found_files" -o ./a.out
fi

echo '[ INFO ] Good! Now I can run the program.'

./a.out
