#!/usr/bin/perl -w
# Copyright (C) Steve Haslam 1999. This is free software.
# Distributable under the terms of the GNU General Public License, version 2
# See the file 'COPYING' for license text.

require 5;
use strict;
use POSIX;
use Debian::ThemeConverters qw[printv printi printw printe wrapsystem wchdir direntries debwalk];

my $delondie;

$SIG{'__WARN__'} = \&printw;
$SIG{'__DIE__'} = sub { printe @_; if ($delondie) { wchdir('/'); wrapsystem("/bin/rm", "-rf", $delondie); } exit 255; };

Debian::ThemeConverters::main \&wmakerthemetodeb;

exit 0;

sub fixthemefile {
  my $filename = shift;
  printv "Fixing up $filename";
  my $outfile = tmpnam;
  my $madechanges = 0;
  open(THEMEFILE, $filename) || die "Can't reade $filename: $!\n";
  open(OUTFILE, ">$outfile") || die "Can't write $outfile: $!\n";
  while (<THEMEFILE>) {
    $madechanges++ if (s@~/GNUstep/Library/WindowMaker/(Backgrounds/)?@@);
    print OUTFILE;
  }
  close THEMEFILE;
  close OUTFILE;
  if ($madechanges) {
    printi "$filename changed";
    unlink($filename) || die "Can't unlink $filename: $!\n";
    rename($outfile, $filename) || die "Can't rename $outfile to $filename: $!\n";
  }
}

sub wmakerthemetodeb {
  my $themepkgfilename = shift;
  my $destdir = shift;

  my $themename = $themepkgfilename;
  $themename =~ s@.*/@@;
  $themename =~ s@.tar.gz$@@;
  $themename =~ s@.tar$@@;
  $themename =~ s@.tgz$@@;

  # Make Debian package name
  # Name convetion entirely invented by me and probably crap
  # "wmaker-xyyzy-theme"
  my $dpkgname = $themename;
  my $dpkgversion = "0.0";
  my $dpkgmaintainer = "Unknown";
  my $dpkgdescription = "Window Maker theme";

  $dpkgname =~ tr/A-Z/a-z/;
  $dpkgname =~ s/[^a-z+.-]//g;
  $dpkgname = "wmaker-$dpkgname-theme";
  printv "Debian package: $dpkgname";

  # Create working area
  my $tmpdir = tmpnam;
  mkdir($tmpdir, 0755) || die "Can't create $tmpdir: $!\n";
  $delondie = $tmpdir;
  printv "Entering directory $tmpdir";
  wchdir($tmpdir);

  # Prepare to get files
  my $installpath = "usr/share/WindowMaker";
  if (wrapsystem("/usr/bin/install", "-d", "$tmpdir/$installpath") != 0) {
    die "$dpkgname: Unable to create directory $tmpdir/$installpath\n";
  }
  wchdir("$tmpdir/$installpath");

  # Unpack original
  if (wrapsystem("/bin/tar", "xzf", $themepkgfilename) != 0) {
    die "$themepkgfilename: Extraction failed\n";
  }

  # Look at results of extractions
  my @stylesheets;
  if (-d "Themes") {
    printv "\"Themes\" directory exists, OK.";
    @stylesheets = debwalk('Themes');
  }
  else {
    @stylesheets = grep { m@\.themed/style$@ } debwalk(".");
    if (@stylesheets == 0) {
      die "$themepkgfilename: Theme file does not contain a \"Themes\" directory or \"*.themed/style\" files\n";
    }
  }

  # Look for .lsm information
  my %lsminfo = Debian::ThemeConverters::readlsminfo('.');
  $dpkgdescription = $lsminfo{'description'} if (exists $lsminfo{'description'});
  $dpkgmaintainer = $lsminfo{'author'} if (exists $lsminfo{'author'});

  # Process theme control files
  foreach (@stylesheets) {
    fixthemefile($_);
  }

  # Move .themed directories into "Themes"
  opendir(DIR, ".");
  my @themeddirs = grep { m@\.themed$@ } readdir(DIR);
  closedir(DIR);
  if (@themeddirs) {
    if (! -d 'Themes') {
      mkdir('Themes', 0755) || die "Can't create \"Themes\": $!\n";
    }
    if (wrapsystem("/bin/mv", @themeddirs, "Themes") != 0) {
      die "$themepkgfilename: Unable to move [@themeddirs] into \"Themes\"\n";
    }
  }
  
  # Make .deb file
  my $dpkgfile = "${dpkgname}_${dpkgversion}_all.deb";
  wchdir $destdir;
  Debian::ThemeConverters::makedeb($dpkgfile, $tmpdir,
				   { Name => $dpkgname,
				     Version => $dpkgversion,
				     Maintainer => $dpkgmaintainer,
				     Description => $dpkgdescription,
				     LongDescription => "This pacakge was automagically created from a WindowMaker theme called $themename"
				   });

  # Clean up
  wchdir('/');
  if (wrapsystem("/bin/rm", "-rf", $tmpdir) != 0) {
    warn "Failed to remove work directory $tmpdir";
  }
  undef $delondie;

  return $dpkgfile;
}

=head1 NAME

wmakerthemetodeb - Convert Window Maker theme to Debian package

=head1 SYNOPSIS

B<wmakerthemetodeb>
[B<-p>]
[B<-i>]
[B<-r> I<command>]
[B<-R> I<command>]
I<tarball>...

=head1 DESCRIPTION

B<wmakerthemetodeb> converts WindowMaker themes in the ".tar.gz" files
named in its command line to ".deb" Debian packages.

With no options, the tarballs will be converted to .deb files only. In
order to do this, the .deb builder (dpkg-deb(1)) need to be run at
least through fakeroot(1). The command used to get "root privileges"
is specified with the B<-r> option.

The B<-i> option will automatically install the converted packages and
then delete the .deb files. In order to install a package, B<real>
root privileges are needed. The command needed to get these is
specified with the B<-R> option, if different from the command given
by B<-r>.

The B<-p> option will cause B<wmakerthemetodeb> to print out which
.deb files were made in a program-parseable fashion. This is used
internally when the B<-r> option is used.

The output will look like this:

    wmakerthemetodeb:I: qw[foo.deb bar.deb quux.deb]

=head1 EXAMPLES

   wmakerthemetodeb -rfakeroot -Rsudo -i Babylon5.tar.gz
   wmakerthemetodeb -rsudo -i AboveEndor.tar.gz

=head1 SEE ALSO

dpkg(1), Debian::ThemeConverters(3pm)

=head1 AUTHOR

Steve Haslam <araqnid@debian.org>

=cut
