#!/bin/bash
# author: William Hom

Usage() {
    echo "--- !!* KA-KAWW *!! ---"
    echo "Usage: mcaw [option] [.ma file] [output]"
    echo "-c    Compile source file to LLVM IR"
    echo "-a    Compile source file to AST and SAST"
    echo "-l    Same as -c, but ignore LLVM errors"
    echo "-h    Print this help"
    exit 1
}

FileErr() {
    echo "-- !! .__macaw.ma exists !! --"
    echo "The Macaw compiler generates this intermediary file and then removes it, but it looks like it already exists in this directory. Since we do not want to overwrite your files, please rename or remove it."
    echo "--- !!* KA-KAWW *!! ---"
    exit 1
}

MissingSrc() {
    echo "-- !! source file not found !! --"
    echo "$1 not found. Please make sure it exists."
    echo "--- !!* KA-KAWW *!! ---"
    exit 1	
}

if [ ! -f macaw.native ]; then
    echo "Macaw native compiler not found! Please run make."
    exit 1
fi


if [ "$#" -ge 1 ]; then

    if [ ! -f _includes/stdlib.ma ]; then
        echo "Macaw Standard Library not found!"
        exit 1
    fi

    if [ -f .__macaw.ma ]; then
        FileErr
    fi

	if [ "$#" -eq 2 ]; then

	    if [ ! -f "$2" ]; then
	    	MissingSrc
	   	fi

	    cat _includes/stdlib.ma > .__macaw.ma
	    cat "$2" >> .__macaw.ma

	    case "$1" in
	        "-c" ) ./macaw.native -c < .__macaw.ma
	               if [ $? -eq 0 ]; then
	                   rm -f .__macaw.ma
	                 else
	                   rm -f .__macaw.ma
	                   exit 1
	               fi
	               exit 0
	               ;;
	        "-a" ) ./macaw.native -a < .__macaw.ma
	               if [ $? -eq 0 ]; then
	                   rm -f .__macaw.ma
	                 else
	                   rm -f .__macaw.ma
	                   exit 1
	                 fi
	               exit 0
	               ;;
	        "-l" ) ./macaw.native -l < .__macaw.ma
	               if [ $? -eq 0 ]; then
	                   rm -f .__macaw.ma
	                 else
	                   rm -f .__macaw.ma
	                   exit 1
	                 fi
	               exit 0
	               ;;
	        *    ) rm -f .__macaw.ma
	               Usage
	               ;; 
	    esac
	elif [ "$#" -eq 1 ]; then
	    if [ ! -f "$1" ]; then
	    	MissingSrc
	   	fi

	    cat _includes/stdlib.ma > .__macaw.ma
	    cat "$1" >> .__macaw.ma

	    ./macaw.native -c < .__macaw.ma
       if [ $? -eq 0 ]; then
           rm -f .__macaw.ma
         else
           rm -f .__macaw.ma
           exit 1
       fi
       exit 0
	else
	    Usage
	fi
fi
