#!/bin/bash

# Compare the compiled CSS of the current commit and the compiled CSS of an old
# commit. Useful for verifying that changes to a Stylus stylesheet, like renamed
# variables or changes to formatting, have no effect on the compiled CSS.

# Usage:
#
# compare-compiled-css
#     Compare the compiled CSS of the current commit and the compiled CSS of the
#     parent commit.
#
# compare-compiled-css -c [hash]
#     Compare the compiled CSS of the current commit and the compiled CSS of the
#     commit with the specified hash.

SCRIPTS=$(dirname $0)
COMPILED_CSS=$SCRIPTS/../media/redesign/css
COMPARISON_DIR=$(mktemp -d)

# $1: The directory where the compiled CSS should be stored
function store_compiled_css {
    mkdir -p $1

    rm $COMPILED_CSS/*.css
    $SCRIPTS/compile-stylesheets &> /dev/null

    cp -a $COMPILED_CSS/*.css $1
}

# Handle the --commit/-c option. This is the only available option, so we don't
# need to loop through $@ as one usually would.
if ([[ "$1" == "-c" ]] || [[ "$1" == "--commit" ]]) && [ -n "$2" ]; then
    OLD_COMMIT=$2
    COMMIT_NAME=$OLD_COMMIT
else
    OLD_COMMIT="HEAD^"
    COMMIT_NAME="the parent commit"
fi

# Status
echo "Comparing..."

# Store the compiled CSS of the current commit
CURRENT_CSS=$COMPARISON_DIR/current
store_compiled_css $CURRENT_CSS

# Store the compiled CSS of the old commit
OLD_CSS=$COMPARISON_DIR/old
git checkout --quiet $OLD_COMMIT
store_compiled_css $OLD_CSS

# Compare the two
diff -qr $OLD_CSS $CURRENT_CSS &> /dev/null
if [ $? -eq 0 ]; then
    echo "OK: The current commit and $COMMIT_NAME compile identical CSS"
else
    echo
    diff -r $CURRENT_CSS $OLD_CSS
    echo
    echo "NOTE: The current commit and $COMMIT_NAME compile different CSS"
fi

# Cleanup
git checkout --quiet -
rm $COMPILED_CSS/*.css
mv $CURRENT_CSS/*.css $COMPILED_CSS
rm -rf $COMPARISON_DIR
