#!/bin/bash

# Error handling
set -e

# For styling/colorizing output
txtbld=$(tput bold)
txtblue=${txtbld}$(tput setaf 4)
txtred=${txtbld}$(tput setaf 1)
txtwhite=${txtbld}$(tput setaf 7)

# Dependency check
function dependencycheck() {
    numdependencies="$#"
    dependencies=("$@")
    missingdependencies=0

    for ((i = 0; i < numdependencies; i++)) ; do
        if ! command -v "${dependencies[$i]}" &> /dev/null ; then
            echo "${txtred}dependency not met: ${dependencies[$i]}${txtwhite}"
            missingdependencies=$((missingdependencies+1))
        fi
    done

    if [ $missingdependencies -gt 0 ] ; then
        echo "${txtred}Please install needed dependencies${txtwhite}"
        exit 1
    fi
}

# Main Dependency check
dependencycheck uglifyjs uglifycss

function uglier() {
    numargs="$#"
    args=("$@")
    for ((i = 0; i < numargs; i++)) ; do

        # grabs the extension string
        extension=$(echo "${args[$i]}" | sed 's/^[^\..:]*[\..]//')

        # minifies js files
        if [[ $extension == "js" ]] ; then
            uglifyjs "${args[$i]}" > "${args[$i]}.min.js"
            echo "${txtblue}uglifyjs minified ${args[$i]} into ${args[$i]}.min.js${txtwhite}"

        # minifies css files
        elif [[ $extension == "css" ]] ; then
            uglifycss "${args[$i]}" > "${args[$i]}.min.css"
            echo "${txtblue}uglifycss minified ${args[$i]} into ${args[$i]}.min.css${txtwhite}"

        else
            echo "${txtred} file type not recognized: ${args[$i]}${txtwhite}"
        fi

    done
    mkdir minified
    mv *.min.* minified
}

uglier "$@"
