use strict;

package AutoPkgBuilder;

use Dpkg::Files;
use FileHandle;
use POSIX qw(strftime);

use base qw(Exporter);
our @EXPORT = qw($APB_HOME
		 apb_init apb_check_built apb_generate_file apb_filter
		 rename_orig apb_add_changelog apb_modify_build_depends
		 open_log set_log msg_time msg ind);

our $APB_HOME;
our $Q;

BEGIN {
    if (exists($ENV{APB_HOME})) {
	$APB_HOME = $ENV{APB_HOME};
    } else {
	print STDERR "Need set environment variable APB_HOME.\n";
	exit(1);
    }
}

sub apb_init {
    if ($ARGV[0] eq '-q') {
	shift(@ARGV);
	$Q = 1;
    }
}

sub apb_check_built {
    my $subdir = shift;
    my $files = new Dpkg::Files("$APB_HOME/build/$subdir") or return undef;
    my $file = $files->file(0);
    return (-f "$APB_HOME/build/$file" || -f "$APB_HOME/binary-sh4/$file");
}

sub apb_generate_file {
    my ($file, $code, $no_msg) = @_;
    my $fh = new FileHandle($file, "w") or die "Can't open $file ($!)";
    msg("Generating $file...") unless ($no_msg);
    my $rv = $code->($fh);
    $fh->close;
    if ($file =~ /\.sh$/) {
	chmod(0755, $file);
    }
    msg("Done.\n") unless ($no_msg);
    return $rv;
}

sub apb_filter {
    my ($ifile, $ofile, $code) = @_;
    my $ifh = new FileHandle($ifile, "r") or die "Can't open $ifile ($!)";
    my $ofh = new FileHandle($ofile, "w") or die "Can't open $ofile ($!)";
    my $rv = $code->($ifh, $ofh);
    $ofh->close;
    $ifh->close;
    if ($ofile =~ /\.sh$/ || -x $ifile) {
	chmod(0755, $ofile);
    }
    return $rv;
}

sub rename_orig {
    my $file = shift;
    return undef unless (-f $file);
    my $orig = "$file.ORIG";
    unless (-f $orig) {
	rename($file, $orig) or die "Can't rename $file ($!)";
    }
    return $orig;
}

sub apb_add_changelog {
    my ($dir, @msg) = @_;
    unless (exists($ENV{DEBEMAIL})) {
	die "Missing DEBEMAIL environment variable";
    }
    unless (exists($ENV{DEBFULLNAME})) {
	die "Missing DEBFULLNAME environment variable";
    }
    my $file = "$dir/debian/changelog";
    my $orig = rename_orig($file) or return undef;
    my $msg = join("\n  ", map {s/^\s+//s; s/\s+$//s; $_} @msg);
    apb_filter($orig, $file, sub {{
	my ($ifh, $ofh) = @_;
	my $date = strftime('%a, %d %b %Y %H:%M:%S %z', localtime);
	$date =~ s/, 0/,  /;
	local $_ = <$ifh>;
	my ($pkg, $version) = /^(\S+)\s+\(([^\)]+)\)/;
	$ofh->print(<<EOF);
$pkg (${version}iohack0) unstable; urgency=low

  * $msg

 -- $ENV{DEBFULLNAME} <$ENV{DEBEMAIL}>  $date

EOF
	do {
	    $ofh->print($_);
	} while (<$ifh>);
    }});
}

sub apb_modify_build_depends {
    my ($dir, $code) = @_;
    foreach my $file ("$dir/debian/control", "$dir/debian/control.in") {
	my $orig = rename_orig($file) or next;
	apb_filter($orig, $file, sub {{
	    my ($ifh, $ofh) = @_;
	    local $_;
	    while (<$ifh>) {
		if (/^Build-Depends:/) {
		    $code->();
		}
		$ofh->print($_);
	    }
	}});
    }
}

my $LOG;

sub open_log {
    my ($name, $default, $notime) = @_;
    my $file;
    if ($notime) {
	$file = "$APB_HOME/log/$name.log";
    } else {
	$file = strftime("$APB_HOME/log/%Y%m%d-$name.log", localtime);
    }
    my $log = new FileHandle($file, "w") or die "Can't open $file ($!)";
    $log->autoflush(1);
    if ($default) {
	$LOG = $log;
    }
    return $log;
}

sub set_log {
    $LOG = shift;
}

sub msg_time {
    my $date = strftime("[%Y-%m-%d %H:%M:%S] ", localtime);
    $LOG->print($date, @_) if ($LOG);
    print STDERR $date, @_;
}

sub msg {
    $LOG->print(@_) if ($LOG);
    print STDERR @_;
}

sub ind {
    return if ($Q);
    if (@_) {
	print STDERR @_;
    } else {
	print STDERR ".";
    }
}

1;
