:
eval 'exec /tools/$MACHINE/bin/perl -S $0 ${1+"$@"}'
    if 0;

use ClearCase::Argv 0.23;
use ClearCase::SyncTree 0.05;
use File::Basename;
use File::Find;
use File::Spec 0.82;
use Getopt::Long;

use constant MSWIN => $^O =~ /MSWin32|Windows_NT/i;

require 5.005 if MSWIN;

my $prog = basename($0, qw(.pl));

sub usage {
    my $msg = shift;
    my $rc = (defined($msg) && !$msg) ? 0 : 2;
    if ($rc) {
	select STDERR;
	print "$prog: Error: $msg\n\n" if $msg;
    }
    print <<EOF;
Usage: $prog [flags] -sbase <dir> -dbase <vob-dir> [pname...]
Flags:
   -help		Print this message and exit
   -dbase <vob-dir>	The destination base directory
   -sbase <dir>		The source base directory
   -flist <file>	A file containing a list of files or "-" for stdin
   -map			Interpret \@ARGV as a hash mapping src => dest
   -force		Continue despite errors
   -ci			Check in changes (default is to leave co'ed)
   -cr			Check in in such a way as to preserve CR's (slower)
   -ctime		Checked in files get current time (no -ptime)
   -rmname		Remove files in dest area that aren't in src
   -label <lbtype>	Apply the specified label when done
   -c <comment>		Use specified comment for checkins
   -n			Exit after showing a preview.
   -yes			Perform all work without asking first
   -testdrive		Do the work, then unco it all and exit
   -nprotect		Turn off "cleartool protect -chmod" stage
   -Narrow [!]<re>	Limit files found to those which match /re/
   -/dbg=1		Verbose mode: show cleartool cmds as they run
Notes:
    All flags may be abbreviated to their shortest unique name.
    Run "perldoc synctree" for detailed documentation and examples.
Examples:
    $prog -sbase /tmp/newcode -dbase /vobs_tps/foo /tmp/newcode
    $prog -sb /tmp/newcode -db /vobs_tps/foo -N '\.java\$' /tmp/newcode
    $prog -sb /tmp/newcode -db /vobs_tps/foo -N '!\.old\$' /tmp/newcode
EOF
    exit $rc;
}

my %transfer;
my %opt;

{
    my($only, $skip);
    sub wanted {
	my $path = File::Spec->rel2abs($File::Find::name);
	$path =~ s%\\%/%g if MSWIN;
	if (! -d && defined $opt{Narrow}) {
	    $only ||= join('|', grep !/^!/, @{$opt{Narrow}});
	    return if $only && $path !~ /$only/;
	    $skip = join('|', map {(m/^!(.*)/)[0]} grep /^!/, @{$opt{Narrow}});
	    return if $skip && $path =~ /$skip/;
	}
	if (-f $_ || -l $_) {
	    $transfer{$path} = $path;
	} elsif (-d _) {
	    if ($_ eq 'lost+found') {
		$File::Find::prune = 1;
		return;
	    }
	} elsif (! -e _) {
	    die "$prog: Error: no such file or directory: $path\n";
	} else {
	    die "$prog: Error: unsupported file type: $path\n";
	}
    }
}

ClearCase::Argv->attropts;
ClearCase::Argv->inpathnorm(0);

local $Getopt::Long::ignorecase = 0;  # global override for dumb default
# A little hack to allow use of flag abbreviations without ambiguity
# warnings, e.g. parse -c <cmnt> independently of -ci etc.
{
    local $Getopt::Long::autoabbrev = 0;
    local $Getopt::Long::passthrough = 1;
    GetOptions(\%opt, qw(comment|c=s nprotect)) || exit 1;
}
GetOptions(\%opt, qw(sbase=s dbase=s flist=s lbtype|label|mklabel=s map
		     Narrow=s@
		     Add Modify Rm
		     ci cr ctime force rmname
		     help preview|n ok yes testdrive
)) || exit 1;
usage() if $opt{help};
usage("-sbase is a required flag") if !$opt{sbase};
usage("-dbase is a required flag") if !$opt{dbase};
for (@opt{qw(dbase sbase)}) {
    die "$prog: Error: no such directory $_\n" unless -d;
    $_ = File::Spec->rel2abs($_);
    s%\\%/%g if MSWIN;
}

if ($opt{flist}) {
    usage("-flist and -map are mutually exclusive") if $opt{map};
    open(FLIST, $opt{flist}) || die "$prog: Error: $opt{flist}: $!";
    while(<FLIST>) {
	chomp;
	s/^\s+//;
	s/\s+$//;
	next if ! $_ || /^#/;
	my($from, $to) = split /\s*=[=>]\s*/;
	next if -d $from;
	die "$prog: Error: $_: No such file or directory\n" unless -e;
	$transfer{$from} = $to || $from;
    }
    close(FLIST);
}

if ($opt{map}) {
    while (@ARGV) {
	my($from, $to) = split /\s*=[=>]\s*/, shift;
	$to ||= shift;
	die "$prog: Error: odd number of files specified with -map\n" if !$to;
	next if -d $from;
	$transfer{$from} = $to;
    }
} else {
    push(@ARGV, $opt{sbase}) if !@ARGV && !%transfer;
    # Convert warnings from within find() into fatal errors.
    local $SIG{__WARN__} = sub { die "$prog: Error: @_" };
    for my $pname (@ARGV) {
	find(\&wanted, $pname);
    }
}

#########################################################################
# At this point we've parsed the cmd line, derived the file list,
# etc. and are set to do the real work.
#########################################################################

# Create a 'synctree' object.
my $sync = ClearCase::SyncTree->new;
# Allow the protect default to be overridden.
$sync->protect(0) if $opt{nprotect};
# Turn off the default exception handler if -force.
$sync->err_handler(0) if $opt{force};
# Specify the comment to attach to any changes.
$sync->comment($opt{comment} || $opt{comment} || "By:$0");
# Suppress -ptime flag on checkins if requested.
$sync->ctime(1) if $opt{ctime};
# Tell it where the files are coming from ...
$sync->srcbase($opt{sbase});
# Tell it where they're going to ...
$sync->dstbase($opt{dbase});
# Supply the list of required files.
$sync->srcmap(%transfer);
# Compare src and dest lists and figure out what to do.
$sync->analyze;
# If -preview, give a preview and exit. Ask for OK to proceed unless -yes.
if (!$opt{yes} || $opt{preview}) {
    my $changes = $sync->preview($opt{rm});
    if (!$changes) {
	if ($opt{rm}) {
	    warn "Warning: -rm behavior cannot be predicted ...\n";
	} else {
	    exit 0;
	}
    }
    exit 0 if $opt{preview};
    my $msg = "Continue with these $changes file changes?";
    $msg = qq("$msg") if MSWIN;
    exit 0 if system(qw(clearprompt proceed -pro), $msg);
}
# Create new elements in the target area.
$sync->add unless $opt{Add};
# Update existing files which differ between src and dest.
$sync->modify unless $opt{Modify};
# Remove any files from dest that aren't in src, if requested.
$sync->subtract if $opt{rm};
# Optionally label the above work, including any still-checked-out files.
$sync->label($opt{lbtype}) if $opt{lbtype};
# Undo all work and exit if we're just going for a test drive.
$sync->fail(0) if $opt{testdrive};
# Workaround for a CC problem - xml files may have binary data.
$sync->eltypemap('\.xml$' => 'compressed_file');
# Get rid of any exception handler before starting the checkin
# process, as once a checkin succeeds there's no going back.
$sync->err_handler(0);
# Prompt the user before checkin if -yes not in use.
if (!$opt{yes} && !$opt{ci}) {
    my $msg = "Check in all changes ('abort' to unco)?";
    $msg = qq("$msg") if MSWIN;
    my $resp = system(qw(clearprompt yes_no -pro), $msg);
    $sync->fail if $resp > 1;
    $opt{ci} = !$resp;
}
# Now check in the changes: one at a time if -cr, otherwise
# all at once.
$sync->no_cr unless $opt{cr};
$sync->checkin if $opt{ci} || $opt{cr} || $opt{yes};

__END__

=head1 NAME

synctree - Normalize a tree of files with a tree of ClearCase elements

=head1 SYNOPSIS

Run this script with the C<-help> option for usage details. Here are
some additional sample usages with explanations:

  synctree -ci -sbase /tmp/newcode -dbase /vobs_tps/xxx /tmp/newcode/xxx

[Take all files located under /tmp/newcode/xxx, remove the leading
"/tmp/newcode", from each of their pathnames, and place the remaining
relative paths under "/vobs_tps/xxx". Check in when done.]

  synctree -cr -sbase /vobs/hpux/bin -dbase /vobs_rel/hpux/bin

[Sync all files under "/vobs_rel/hpux/bin" with those in
"/vobs/hpux/bin", making sure to preserve their CR's.]

  synctree -sb /A/B -db /X/Y -map /A/B/foo /X/Y/bar /A/B/here /X/Y/there

Take 'foo' from directory /A/B and check it in as 'bar' in /X/Y.
Similarly for 'here' and 'there'.

=head1 DESCRIPTION

Brings a VOB area into alignment with a specified set of files from a
source area. This is analogous in some ways to clearexport_* and
clearimport but those cannot work incrementally; they do an
all-or-nothing import. Synctree is useful if you have a ClearCase tree
that must be kept in sync with a CVS tree during a transition period,
or for overlaying releases of third-party products upon previous ones,
or exporting deliverable files from a nightly build to a release VOB
while preserving CR's, or similar.

The default operation is to mkelem all files which exist in
I<E<lt>srcE<gt>> but not in I<E<lt>destE<gt>>, modify any files which
exist in both but differ, but B<not> to remove files which are present
in I<E<lt>destE<gt>> and not in I<E<lt>srcE<gt>>.  The I<-rm> flag will
cause this removal to happen as well.

This script must run in a view context; the branching behavior of any
checkouts it makes will be governed by the view's config spec.  Also,
the directory named by the I<-dbase> flag must exist and lie under a
mounted VOB tag.

The list of source files to operate on may be provided with the
I<-flist> option or it may come from C<@ARGV>. Any directories
encountered on C<@ARGV> will be traversed recursively. If no
source-file-list is provided at all, the directory specified with
I<-sbase> is treated as the default.

File paths may be given as relative or absolute; all filenames are
turned into absolute paths, then the path given with the I<-sbase>
parameter is removed and replaced with that of I<-dbase> to produce the
destination pathname.

Symbolic links are supported, even on Windows.  Note that the text of
the link is transported I<verbatim> from source area to dest area; thus
relative symlinks may no longer resolve in the destination.

Consider using the I<-n> or I<-testdrive> flags the first time you use
this on a valued VOB, even though nothing irreversible is done (e.g.
no I<rmelem>, I<rmbranch>, I<rmver>, I<rmtype>, etc.).  And by the same
token use I<-ci> and I<-yes> with care.

=head1 FILE MAPPING

Synctree has lots of support for remapping filenames. The options can
be pretty confusing and thus deserve special treatment.

All mapping is enabled with the B<-map> flag.  Without I<-map>, a list
of files provided on the command line is interpreted as a set of
I<from> files; their I<to> paths are derived via I<s/^sbase/dbase/> and
thus the file basenames do not change. However, in the presence of
I<-map> the @ARGV is instead interpreted as a hash alternating B<from>
and B<to> names.  Thus

  synctree -sbase /etc -dbase /vobs_etc /etc/passwd /etc/group

would make two files under /vobs_etc called passwd and group, whereas

  synctree -sbase /etc -dbase /vobs_etc -map /etc/passwd /vobs_etc/foo

would create one file (/vobs_etc/foo) which is a copy of /etc/passwd.
Alternatively the mapping may be specified with a literal B<=E<gt>>:

  synctree -sb /etc -db /vobs_etc -map '/etc/passwd => /vobs_etc/foo' ...

but note that this must be quoted. The I<=E<gt>> style is also allowed
in files specified via B<-flist>, thus:

  synctree -sb /etc -db /vobs_etc -map -flist - << EOF
  /etc/passwd => /vobs_etc/foo
  /etc/group  => /vobs_etc/bar
  EOF

=head1 COMPARISONS

Synctree is comparable to I<citree> and I<clearfsimport>. It is similar
to citree but runs on both Windows and UNIX. It has the following
advantages over clearfsimport:

=over 4

=item *

Synctree works with ClearCase versions prior to 4.1.

=item *

Synctree handles C<MVFS->MVFS> transfers while preserving CR's whereas
clearfsimport does C<flat_file_system->MVFS> only.

=item *

Synctree has support for mapping filenames in transit and a I<-Narrow>
option for limiting the set of files to transfer.

=item *

Synctree is built on an API (B<ClearCase::SyncTree>) which aids custom
tool development in Perl whereas clearfsimport is a command-line
interface only.

=item *

Synctree may at some point (but does not yet) have support for
I<element retention>. I.e. if an element is added in one pass and
removed (rmnamed) in a subsequent pass, and if a third pass would make
another element of the same name, synctree could optionally make a link
to the existing file instead of creating what might be a "evil twin".

=back

However, unless one of the above applies the supported, integrated
solution (B<clearfsimport>) is generally preferable. And of course all
of these features I<may> eventually be supported by clearfsimport.

=head1 DEBUGGING

The special flag I<-/dbg=1> will cause all underlying cleartool
commands to be printed as they are run (this is actually a feature of
the Argv module on which I<synctree> is built).

=head1 AUTHOR

David Boyce <dsb@world.std.com>

=head1 COPYRIGHT

Copyright (c) 2000 David Boyce. All rights reserved.  This Perl
program is free software; you may redistribute and/or modify it under
the same terms as Perl itself.

=head1 STATUS

This is currently ALPHA code and thus I reserve the right to change the
UI incompatibly. At some point I'll bump the version suitably and
remove this warning, which will constitute an (almost) ironclad promise
to leave the interface alone.

=head1 PORTING

The guts of this program are in the ClearCase::SyncTree module, which
is known to work on Solaris 2.6-7 and Windows NT 4.0SP3-5, and with
perl 5.004_04 and 5.6. The I<synctree> wrapper program per se has had
only rudimentary testing on Windows but appears to work fine there.

=head1 SEE ALSO

perl(1), "perldoc ClearCase::SyncTree"

=cut
