#!/bin/bash
#set -x
clear
########################################################################
###
##
#
# Author: Stéphane HUC
# mail: devs@stephane-huc.net
# gpg:fingerprint: CE2C CF7C AB68 0329 0D20  5F49 6135 D440 4D44 BD58
#
# License: Public Domain
#
# Git:
#
# Date: 2020/05/10
#
##
###
########################################################################

ROOT="$(dirname "$(readlink -f -- "$0")")"
minifier="/usr/bin/java -jar $ROOT/yuicompressor-2.4.8.jar"

#SH="b"
declare -a exts=(css js)

########################################################################
#printf '%s\n' "Write a root folder (where css/js folders exists!): "
#read -r dir
dir="$1"

if [ ! -d "${dir}" ]; then printf '%s\n' "[ KO ] The script '$0' stop, because the dir '${dir}' not exists!"; exit; fi

for ext in "${exts[@]}"; do

	if [ -d "$dir/${ext}/" ]; then
		while read -r file; do
			#echo "$(basename $file)"
			file_seconds=0
			mini_seconds=0
			
			if [ -f $file ]; then
				search=".min.$ext"; #echo "search: $search";
				if [[ "$(basename $file)" != *"$search"* ]]; then
					printf '%s%s\n' "file: " "${file}";

					#case "$SH" in
						#"b") mini="${file/.${ext}/.min.${ext}}" ;;
						#"k") mini="${file%.$ext}.min.$ext" ;;
					#esac
					mini="${file/.${ext}/.min.${ext}}"
					printf '%s%s\n' "futur minified: " "${mini}"

					if [ -x $(which stat) ]; then
						#case "$SH" in
						#"b")
						[ -f "$file" ] && file_seconds=$(stat -c "%Y" "$file")
						[ -f "$mini" ] && mini_seconds=$(stat -c "%Y" "$mini")
						#;;
						#"k")
							#[ -f "$file" ] && file_seconds=$(stat -f "%m" "$file")
							#[ -f "$mini" ] && mini_seconds=$(stat -f "%m" "$mini")
						#;;
						#esac

					else
						[ -f "$file" ] && file_seconds=$(date -r "$file" +%s)
						[ -f "$mini" ] && mini_seconds=$(date -r "$mini" +%s)

					fi
					printf '%s%s\n' "file mtime: " "${file_seconds}" 
					printf '%s%s\n' "file.min mtime: " "${mini_seconds}" 

					if [ "${file_seconds}" -gt "${mini_seconds}" ]; then
						#printf "file: $file_seconds sec | name: $mini_seconds sec\n";
						if $minifier "${file}" -o "${mini}" --charset utf-8 --type "${ext}"; then
							printf "[ %s ] %s\n" "OK" "file $file minified to $mini"

						else
							printf "[ %s ] %s\n" "KO" "Can not minify file $file to $mini!"
						fi
					fi

					unset file_seconds mini mini_seconds
				fi
			fi

		done <<EOF
$(find "$dir/${ext}/" -maxdepth 1 -type f -name "*.${ext}")
EOF
	fi
done

unset ROOT minifier dirs
