#!/usr/bin/perl
# Copyright (c) 2010 Symbian Foundation Ltd
# This component and the accompanying materials are made available
# under the terms of the License "Eclipse Public License v1.0"
# which accompanies this distribution, and is available
# at the URL "http://www.eclipse.org/legal/epl-v10.html".
#
# Initial Contributors:
# Mike Kinghan, mikek@symbian.org for Symbian Foundation Ltd - initial contribution.

# Script to diff this package with the upstream revsion on which it is
# baselined.

use strict;
use get_baseline;
use perl_run;
use places;
use get_hostplatform_dir;
use File::Spec;
use Cwd 'abs_path';
use Getopt::Long;

my $help =0;
my $baseline_dir = '';
my $diff_out = '';
my @excludes = ('*.hg*','*cross-plat-dev-utils*','*baseline.txt','*README','*TODO','*NEWS','*.pyc','*~');

sub usage(*);
sub usage_error($);
sub help();

GetOptions("help=i" => \$help, "diff-file=s" => \$diff_out,
	"baseline-dir=s" => \$baseline_dir) or usage_error("Usage error");

if ($help) {
	help();
}
if (!$baseline_dir) {
	usage_error("Need -b, --baseline-dir");
}
print ">>> Testing for diff\n";
my $diff_test = "diff --version";
my $devnull = File::Spec->devnull();
print ">>> Executing: $diff_test\n";
my $rc = system("$diff_test > $devnull") >> 8;
die "*** Error: can't execute the diff tool: $rc ***", if ($rc);
$baseline_dir = abs_path($baseline_dir);
perl_run("get_upstream.pl $baseline_dir") and die $!;
my $epocroot = get_epocroot();
my $build_pkg_dir = get_pkg_dir();
$baseline_dir = File::Spec->catfile("$baseline_dir","build");
my $host_platform_dir = get_hostplatform_dir();
push(@excludes,"*$host_platform_dir*");
foreach my $exclude (@excludes) {
	$exclude = "-x '$exclude'";
}
my $diff_cmd;
if (!$diff_out) {
	my $baseline_rev = get_baseline();
	$diff_out = File::Spec->catfile("$build_pkg_dir","cross-plat-dev-utils",
		"patch-files","diffs","patch-$baseline_rev.patch");
}
open DIFF,">$diff_out" or die $!;
print DIFF "## diff generated by diff_upstream.pl\n";
close DIFF;
$diff_cmd = "diff -u -r -b -B -E @excludes $baseline_dir $build_pkg_dir >> $diff_out";
print ">>> Executing: $diff_cmd\n";
exit system($diff_cmd) >> 8;

sub usage(*)
{
	local *OUT = shift;
	print OUT "This script diffs this package with upstream package at the " .
		" baseline revision in ../baseline.txt\n" .
		"Options:\n" .
		"-h, --help:              Display this help and exit\n" .
		"-d, --diff-file FILE:    The diffs will be written to FILE. " .
			"Default ./patch-files/diffs/patch-N, where N is the baseline revision\n" .
		"-b, --baseline-dir DIR:  The upstream baseline will be cloned into " .
			"DIR if this does not seem to have been done already. Otherwise " .
			"DIR/build will be udated to the baseline revision before diffing\n" .
		"*** It is assumed that the command 'diff' will invoke the diff tool " .
		"***\n";
}

sub usage_error($)
{
	my $diag = shift;
	print STDERR "*** $diag ***\n";
	usage(*STDERR);
	exit 1;
}

sub help()
{
	usage(*STDOUT);
	exit 0;
}

