#!/bin/env perl -lw
# 
# $Id: pkgmanifest 830 2006-09-19 18:23:08Z comand $
#
# Copyright 2006 Cory Omand <comand@blastwave.org>
# All rights reserved.  Use is subject to license terms.
#
# Redistribution and/or use, with or without modification, is
# permitted.  This software is without warranty of any kind.  The
# author(s) shall not be liable in the event that use of the
# software causes damage.
#
# pkgmanifest - strip one or more path levels from a list of files.
#

use strict;
use File::Basename;
use File::Spec::Functions qw/splitdir catdir/;
use Getopt::Long qw/:config no_ignore_case gnu_getopt/;

my $self = basename $0;
my $VERSION = "1.0";

# Get command line options
my ($strip_path, $prefix);
my $include_prefix = 0;
my $depth = 0;
GetOptions(
    'strip|s=s'  => \$strip_path,
    'prefix|p=s' => \$prefix,
    'depth|d=s'  => \$depth,
    'incprefix!' => \$include_prefix,
    'help|h'     => \&usage,
    'version|V'  => sub {
        print STDERR "$self v$VERSION\n";
        exit 2;
    },
) or usage();

sub usage {
    print STDERR "Usage: $self [--prefix <path>] [--depth <int>] [--no|incprefix] [--strip <path>] < path_list\n";
    exit 1;
}

my $pf_elems = scalar splitdir($prefix) if $prefix;
$pf_elems  = 0 unless $pf_elems;
$pf_elems += $depth;

my %paths;
foreach (<>) {
    chomp; 
    s/^$strip_path// if $strip_path;

    unless (-d) {
        my @path = splitdir(dirname($_));
        for (my $i = 0; $i <= $#path; $i++) {
            my $npath = catdir(@path[0..$i]);
            $paths{$npath}++ if $i >= $pf_elems;
        }
    }
    $paths{$_}++;
}

foreach (sort keys %paths) {
    next if /^$prefix$/ and not $include_prefix;
    print;
}

