package IPM_Util;
require Exporter;
@ISA = qw(Exporter);
# symbols to export by default
@EXPORT = qw(Tar UnTar ReadFile WriteFile scan_dir GetFlist);

use strict;
my $OS = $^O eq "MSWin32" ? "Win32" : "Unix";
if ($OS eq "Win32") {
    eval ("use Archive::Tar;");
    die "ERROR: Archive::Tar is not installed\n" if $@;
}

1;


sub Tar
{
    my ($tarfile, @files) = @_;
    my $OS = $^O eq "MSWin32" ? "Win32" : "Unix";


    if ($OS eq "Unix") {
        my $flist = join(" ", @files);
        system("tar -cf - $flist | gzip > $tarfile");
    }
    else {
        my @newfiles = ();
        my $f;
        foreach $f (@files) {
            if (-f $f) {
                push(@newfiles, $f);
            }
            elsif (-d $f) {
                my @foo = scan_dir($f);
                push(@newfiles, @foo);
            }
        }
        my $tar = Archive::Tar->new();
        $tar->add_files(@newfiles);
        $tar->write($tarfile, 1);
    }
}


sub UnTar
{
    my ($tarfile) = @_;
    my $OS = $^O eq "MSWin32" ? "Win32" : "Unix";

    if ($OS eq "Unix") {
        system("gzip -dc $tarfile | tar -xf -");
    }
    else {
        my $tar = Archive::Tar->new();
        $tar->read($tarfile,1);
        my @filenames = $tar->list_files();
        $tar->extract(@filenames);
    }
}


sub ReadFile   # (filename)
{
    # read file in ascii mode
    my ($data);
    open (IN, "$_[0]") || return undef;
    read (IN, $data, (-s IN));
    close IN;
    return $data;
}


sub WriteFile   # (filename , data)
{
    # save file in ascii mode
    open (OUT, ">$_[0]") || die "Error: Can't create $_[0]\n";
    print OUT $_[1];
    close OUT;
}


sub scan_dir
{
    # recursively get a list of files that match a pattern
    my($dir, $pattern) = @_;
    my @subdirs = $dir;
    my(@files, $e);

    while (@subdirs) {
        $dir = shift @subdirs;
        opendir(DIR, $dir) || die "$0: error opening directory $dir: $!\n";
        while (defined($e = readdir(DIR))) {
            if ($e eq "." || $e eq "..") {  # directory
            }
            elsif (-d "$dir/$e") {  # directory
                push(@subdirs, "$dir/$e");
            } elsif ((!$pattern) || $e =~ /$pattern/) {     # .pod or .pm
                push(@files, "$dir/$e");
            }
        }
    }
    closedir(DIR);
    return sort @files;
}



sub GetFlist
{
    # get list of files in directory

    my ($dir) = @_;
    my @flist;
    opendir(DIR, $dir) || die "can't opendir $dir: $!";
    @flist = readdir(DIR);
    closedir DIR;
    @flist = grep ( !/^(\.|\.\.)$/ , @flist);
    @flist = sort @flist;
    #@flist = grep (-f "$dir/$_", @flist);
}

