#!/usr/bin/perl

# Find installed version of toolchain-source
$inst_ver=`dpkg -s toolchain-source | grep Version`;
$inst_ver=~ s/^Version: //;
chop($inst_ver);

# Investigate the package we are about to upgrade
open(F, '<debian/control') || die "Unable to open debian/control";
while(<F>) {
	if (/^Source: (.*?)-/) {$pkg=$1;}
	if (/^Build-Depends: .*?toolchain-source\s*\((.*?)\)/) {$dep_ver=$1;}
}
close(F);

# Some sanity checks to make sure we can preform an upgrade
if ($pkg ne 'gcc' && $pkg ne 'binutils' && $pkg ne 'gdb') {
	die "Package name does not start with gcc-, binutils-, or gdb-";
}
if ($dep_ver !~ /^=(.+)$/) {
	die "No exact version Build-Depend on toolchain-source found";
} else {
	$dep_ver=$1;
}
if (!system("dpkg --compare-versions $inst_ver \\< $dep_ver")) {
	die "Installed toolchain-source ($inst_ver) not newer than Build-Depend ($dep_ver)";
}
if (!system("dpkg --compare-versions $dep_ver \\< 3.2-100")) {
    die "Unable to upgrade due to large changes in build process.\nPlease recreate your package with tpkg-make";
}

# Decide new version of source code
if (`ls -l /usr/src/toolchain/$pkg.tar.bz2` =~ / -> $pkg-(.*?).tar.bz2$/) {
	$src_ver=$1;
}

# Find epoch and current version from changelog
open(F, '<debian/changelog') || die "Unable to open debian/changelog";
while(<F>) {
	if (/^$pkg-.*?\((.*?)\)/) {
		$cur_ver=$1;
		if ($cur_ver =~ /^(\d+\:)/) {
			$epoch=$1;
		} else {
			$epoch='';
		}
		last;
	}
}
close(F);
$new_ver=$epoch.$src_ver."-1";

# Update changelog
if (!system("dpkg --compare-versions $new_ver \\< $cur_ver")) {
	system("dch 'Recompiled with toolchain-source $inst_ver'");
} else {
	system("dch -v$new_ver 'New upstream release ($src_ver)'");
}

# Update Build-Depends
open(I, '<debian/control') || die "Unable to open debian/control";
open(O, '>debian/control.tmp') || die "Unable to open debian/control.tmp";
while(<I>) {
	if (/^(Build-Depends: .*?)toolchain-source\s*\(.*?\)(.*)$/) {
		print O $1, "toolchain-source (=$inst_ver)", $2, "\n";
	} else {
		print O $_;
	}
}
close(I);
close(O);
system("mv debian/control.tmp debian/control");
