#!/bin/sh -e
#
# https://www.dioptre.fr/bin/smc
# Copyright 2020 Damien Riou <contact@dioptre.fr>
#
# Permission to use, copy, modify, and/or distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
#

main() {
        test -n "$1" || usage
 	test -d "$1" || no_dir "$1"
        test -n "$2" || usage
 	test -d "$2" || no_dir "$2"

        src="${1%/}"
        dst="${2%/}"
        cp -R "$src"/. "$dst" && cd "$dst"
        files=$(list_files)

        echo "$files" | while read -r file
        do
                case "${file##*.}" in
                        html|xml) minify_xml "$file" && compress "$file";;
                        css) minify_css "$file" && compress "$file";;
                        *) compress "$file";;
                esac
        done

        echo "$files" >&2
        printf '[smc] ' >&2
        print_status 'file' 'files' "$files" >&2
	echo >&2
}

usage() {
        echo "usage: ${0##*/} src dst" >&2
	exit 1
}

no_dir() {
	echo "${0##*/}: $1: No such directory" >&2
	exit 2
}

print_status() {
	test -z "$3" && printf 'no %s' "$2" && return

	echo "$3" | awk -v singular="$1" -v plural="$2" '
	END {
		if (NR==1) printf NR " " singular
		if (NR>1) printf NR " " plural
	}'
}

list_files() {
        find . -type f -a \( \
                -name "*\.html" -o \
                -name "*\.css" -o \
                -name "*\.js" -o \
                -name "*\.xml" \)
}

minify_xml() {
        sed -i 's/<\!\-\-.*\-\->//g;s/^\s*//g;s/\s*$//g;/^$/d' "$1"
}

minify_css() {
        sed -i 's|\/\*.*\*\/||g;:a;N;$!ba;s/\n/ /g;s/\([^a-z0-9]\)\s*/\1/g;s/\s*\([^a-z0-9]\)/\1/g;s/\;\}/\}/g' "$1"
}

compress() {
        test "$(stat -c %s "$1")" -ge 300 && gzip -9 < "$1" > "$1.gz" || continue
}

main "$@"
