#!/bin/sh
#
# Copyright 2012 Intel Inc.
#
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
#
# This script builds and runs GM in current workspace with another Skia
# revision user specifies, and then compares their results. This script is
# useful when developers want to know whether their changes would cause any
# regression.
#
# As the name of this script tells, it only works for git repository. :)
#
# Usage:
#   Put this script into where your PATH can find it.
#   And then invoke:
#       $ git skia-verify [sha1-to-compare-default-is-HEAD^]
#   It would delete {before,after,diff} directory under the current directory,
#   so be warned!
#   After it's done, check out diff/index.html for the possible differences.


function say() {
    # set color to yellow
    tput setaf 3
    echo $1
    tput sgr0
}

function warn() {
    # set color to red
    tput setaf 1
    echo $1
    tput sgr0
}

REVISION="HEAD^"

if [[ $# -eq 1 ]];
then
    REVISION="$1"
fi

tput clear

say "Checking sanity..."
git diff --exit-code > /dev/null
if [[ $? -ne 0 ]];
then
    warn "You have uncommitted changes!"
    exit 1
fi
git diff --cached --exit-code > /dev/null
if [[ $? -ne 0 ]];
then
    warn "You have uncommitted changes!"
    exit 1
fi

say "Preparing Directories..."
rm -rf {before,after,diff}
mkdir {before,after,diff}

PREVIOUS_BRANCH=`git branch --no-color | grep "^*" | awk '{ print $2}'`

say "Running GM for current revision..."
./gyp_skia
make BUILDTYPE=Release -j10
if [[ $? -ne 0 ]];
then
    warn "Failed to compile!"
    exit 1
fi
./out/Release/gm -w after

say "Running GM for revision $REVISION..."
# we run the test in a detached branch
git checkout --detach "$REVISION"
./gyp_skia
make BUILDTYPE=Release -j10
if [[ $? -ne 0 ]];
then
    warn "Failed to compile!"
    say "Back to original revision..."
    git checkout "$PREVIOUS_BRANCH"
    exit 1
fi
./out/Release/gm -w before

say "Back to original revision..."
git checkout "$PREVIOUS_BRANCH"

say "Comparing..."
./out/Release/skdiff before after diff