#!/usr/bin/perl 
#
# dh_make - Script to Debianize a source archive
#
use Getopt::Long;

# Some important parameters
$DHLIB="/usr/share/debhelper/dh_make";
$POLICY_VERSION="3.0.1";
$DH_MAKE_VERSION="0.21";
%PACKAGE_TYPES = ( 's' => 'Single', 'l' => 'Library', 'm' => 'Multi-Binary');

$email="";
$username="";
$package_name="";
$cap_package_name="";
$version="";
$fullname = "";
$source_file="";
$debian_native = 0;
$package_type="";
$CHANGELOG="";
my $dummy;

sub process_file(@)
{
   my ($infile, $outfile) = @_;  
   my $line;

    open IN, "<$infile" or die "Unable to open template file $infile for reading: $! \n";
    open OUT, ">$outfile" or die "Unable to open file $outfile for writing: $! \n";
    while (defined($line = <IN>))
    {
      $line =~ s/#PACKAGE#/$main::package_name/g;
      $line =~ s/#UCPACKAGE#/$main::uc_package_name/g;
      $line =~ s/#VERSION#/$main::version/g;
      $line =~ s/#EMAIL#/$main::email/g;
      $line =~ s/#DATE#/$main::date/g;
      $line =~ s/#SHORTDATE#/$main::shortdate/g;
      $line =~ s/#CHANGELOGS#/$main::CHANGELOG/g;
      $line =~ s/#CONFIGURE#/$main::CONFIGURE/g;
      $line =~ s/#INSTALL#/$main::INSTALL/g;
      $line =~ s/#CLEAN#/$main::CLEAN/g;
      $line =~ s/#USERNAME#/$main::username/g;
      $line =~ s/#POLICY#/$main::POLICY_VERSION/g;

      print OUT $line;
    }
    close IN;
    close OUT;
}

sub show_version
{
  print "dh_make - Script to Debianize a regular source archive, version $main::DH_MAKE_VERSION\n";
}
sub show_help
{
  show_version();
  print <<EOF
  Usage: dh_make [options]
  -e, --email <address>     use <address> as the maintainer e-mail address
  -n, --native              the program is Debian native, don\'t generate .orig
  -f, --file <file>         specify file to use as the original source archive
  -s, --single              set package class to single
  -m, --multi               set package class to multiple binary
  -l, --library             set package class to library
  -h, --help                display this help screen and exit
  -v, --version             show the version and exit

By Craig Small <csmall\@debian.org> and Christoph Lameter <clameter\@debian.org>.
EOF
}

sub parse_args
{
  my ($dohelp,$doversion, $single,$multi,$library);
  %options = (email => \$main::email,
              file => \$main::source_file,
	      help => \$dohelp,
	      version => \$doversion,
	      native => \$main::debian_native,
	      single => \$single,
	      multi => \$multi,
	      library => \$library
	      );
  if (GetOptions(\%options, "email=s", "file=s", "help", "version", "native", "single", "multi", "library") == 0)
  {
    show_help();
    exit;
  }
  if ($doversion)
  {
    show_version();
    exit;
  }
  if ($dohelp)
  {
    show_help();
    exit;
  }
  if ($single)
  {
    $main::package_type = 's';
  }
  if ($multi)
  {
    $main::package_type = 'm';
  }
  if ($library)
  {
    $main::package_type = 'l';
  }

}

sub get_username
{
  my $tmpusername;

  $tmpusername =`awk -F: -vUSER=$ENV{LOGNAME} '\$1 == USER \{ print \$5; \}' /etc/passwd | cut -f1 -d,`;
  chomp($tmpusername);
  return $tmpusername if ($tmpusername ne "");
  
  if (-x '/usr/bin/ypmatch')
  {
    $tmpusername=`ypmatch $ENV{LOGNAME} passwd.byname|awk -F: '\{ print \$5; \}'`;
  }
  return $tmpusername if ($tmpusername ne "");

  if (-x '/usr/bin/ldapsearch')
  {
    $tmpusername=`ldapsearch uid=$ENV{LOGNAME} gecos | grep ^gecos | head -1 | awk -F= '\{ print \$2; \}'`;
  }
  return $tmpusername if ($tmpusername ne "");

  return "unknown";
}

sub get_email() 
{
  if ($ENV{DEBEMAIL} )
  {
    return $ENV{DEBEMAIL};
  }
  if ($ENV{EMAIL} )
  {
    return $ENV{EMAIL};
  }
  if ($ENV{LOGNAME} )
  {
    my $mailhost;
    chomp($mailhost = `cat /etc/mailname`);
    return  ($ENV{LOGNAME} . '@' . $mailhost);
  }
}

sub get_package
{
  my $pwd = `pwd`;

  if ($pwd =~ /.*\/(.*)-([0-9][0-9a-zA-Z+\.\-]*)$/)
  {
    $main::package_name = $1;
    $main::uc_package_name = uc $1;
    $main::version = $2;
    $main::fullname = $1 . "-"  . $2;
  } else {
    print "The directory name must be <package>-<version> for dh_make to work!\n";
    print "No underscores allowed!\n";
    exit 1;
  }
}

sub get_date
{
  my $tmpdate;
  if (-x "/usr/bin/822-date")
  {
    $tmpdate = `/usr/bin/822-date`;
    chomp($tmpdate);
    return $tmpdate;
  } else {
    die "Unable to find 822-date program in /usr/bin!\n";
  }
}

$username = get_username();
$email = get_email();
$date = get_date();
$shortdate = `date '+%B %e, %Y'`;
chomp $shortdate;
parse_args();
get_package();

while ($package_type eq "")
{
  print "\nType of package: single binary, multiple binary, or library? [s/m/l] ";
  $type = <STDIN>;
  chomp($type);
  print "\n";
  $type = lc($type);
  $main::package_type = 's' if $type eq 's';
  $main::package_type = 'm' if $type eq 'm';
  $main::package_type = 'l' if $type eq 'l';
}

# Print what we have found
print "Maintainer name : $username\n";
print "Email-Address   : $email \n";
print "Date            : $date\n";
print "Package Name    : $package_name\n";
print "Version         : $version\n";
print "Type of Package : ";
if (exists $PACKAGE_TYPES{$package_type})
{
  print $PACKAGE_TYPES{$package_type};
} else {
  print 'unknown';
}
print "\nHit <enter> to confirm: ";
$dummy = <STDIN>;

if (! $debian_native)
{
  if ($source_file)
  {
    if (-f $source_file)
    {
      system('cp', '-a', "$source_file", "../$package_name\_$version.orig.tar.gz");
    } else {
      print "Source archive you specified was not found!\n";
      exit 1;
    }
  } else {
    if (-d "..$fullname.orig")
    {
      print "Skipping copying to $fullname.orig since $fullname.orig exists.\n";
    } else {
      system('cp', '-a', "../$fullname", "../$fullname.orig");
    }
  }
}
# Figure out where documentation is
@DOCS= split /[ \n]/, `ls -1 N[Ee][Ww][Ss] *[Ff][Aa][Qq]* *.[Tt][Xx][Tt] *[Ii][Nn][Ss][Tt][Aa][Ll][Ll] README* *.README [rR]eadme* *.[rR]eadme [Bb][Uu][Gg][Ss] *[tT][oO][dD][oO]* 2>/dev/null`;
# What are our info files
@INFOS= split /[ \n]/, `find . -regex '.*\\.info\\(-[0-9]+\\)?'`;
# Figure out where is the first changelog, assign other similar files to docs
@changelogs= split /[ \n]/, `ls *[cC][hH][aA][nN][gG][eE][lL][oO][gG]* [cC][hH][aA][nN][gG][eE][sS]* 2>/dev/null`;
$CHANGELOG = $changelogs[0] if ($#changelogs != -1);
shift @changelogs;
@DOCS = (@DOCS,@changelogs);

# Setup debian/rules
if (-x "./configure" )
{
  $CONFIGURE='./configure --prefix=/usr --mandir=\$${prefix}/share/man --infodir=\$${prefix}/share/info';
  $INSTALL='$(MAKE) install prefix=`pwd`/debian/tmp/usr';
  $CLEAN='$(MAKE) distclean';
} else {
  if (! -f 'Makefile' && ! -f 'makefile' && ! -f 'GNUmakefile')
  {
    print "Currently there is no top level Makefile. This may require additional tuning.\n";
  }
  $CONFIGURE="";
  $INSTALL='$(MAKE) install DESTDIR=`pwd`/debian/tmp';
  $CLEAN='$(MAKE) clean';
}

# Customize files
if ( ! -d 'debian')
{
  mkdir 'debian', 0755 or die "Unable to make debian subdirectory: $! \n";
} else {
  print "You already have a debian/ subdirectory in the source tree.\n";
  print "dh_make will not try to overwrite anything.\n";
  exit 1;
}
chdir 'debian' or die "Unable to chdir to debian subdirectory: $! \n";

if ( ! -d $DHLIB )
{
die "Unable to find dh_make's template directory: $! \n";
}

# General Files
@filenames= split /[ \n]/, `(cd $DHLIB/debian && ls)`;
foreach $filename (@filenames)
{
  process_file("$DHLIB/debian/$filename", $filename);
}

# Special Files
@filenames = split /[ \n]/, `(cd $DHLIB/debian$package_type && ls)`;
foreach $filename (@filenames)
{
  process_file("$DHLIB/debian$package_type/$filename", $filename);
}

open (DOCSFILE,">docs");
foreach $doc (@DOCS)
{
    print DOCSFILE "$doc\n";
}
close (DOCSFILE);

if ($#INFOS > -1)
{
    open (INFOFILE,">info");
    foreach $info (@INFOS)
    {
        $info =~ s/^\.\///;
        print INFOFILE "$info\n";
    }
    close (INFOFILE);
}

if ($debian_native)
{
  @filenames= split /[ \n]/, `(cd $DHLIB/native;ls)`;
  foreach $filename (@filenames)
  {
    process_file("$DHLIB/native/$filename", $filename);
  }
}

@filenames = split /[ \n]/, `ls package* 2>/dev/null`;
if ($#filenames != -1)
{
  foreach $filename (@filenames)
  {
    my $oldname = $filename;
    $filename =~ s/^package/$package_name/;
    system('mv', $oldname, $filename);
  }
}
chmod 0755, 'rules';

if ($CONFIGURE ne "")
{
  print "Done. Please edit the files in the debian/ subdirectory now. $package_name\n";
  print "uses a configure script, so you probably don't have to edit the Makefiles.\n";
} else {
  print "Done. Please edit the files in the debian/ subdirectory now. You should also\n";
  print "check that the $package_name Makefiles install into \$DESTDIR and not in / .\n";
}

exit 0;
