#!/bin/sh -- # This comment tells perl not to loop!
#
#ident		"@(#)syncprotos.sh 1.2     94/02/23 SMI"
#
#  syncprotos.sh
#
#	Copyright (c) 1994 by Sun Microsystems, Inc.
eval 'exec /usr/dist/exe/perl -S $0 ${1+"$@"}'
if 0;

#
# Constants/Globals
#
$name = "syncprotos.sh";
$name =~ s/\.sh$//;

#
# usage ()
#
sub usage {
	print STDERR
	  "Usage:  $name -P <proto>,<proto>[,...] -p <pkgdir> -a <arch>\n";
	exit 1;
}

#
# mkpath (path)
#
# Ensure all directory components of a path exist.
#
sub mkpath {
	local($path) = @_;

	$path =~ s/^\///;
	local(@plist) = split(/\//, $path);
	local($mpath) = "";
	while ($#plist > 0) {
		$mpath .= "/" . shift(@plist);
		mkdir($mpath, 0777) if (! -d $mpath);
	}
}

#
# copyfile (from, to)
#
sub copyfile {
	local($from, $to) = @_;
	local(*FROM, *TO);

	unlink($to) if (-f $to);
	if (! open(FROM, $from)) {
		printf STDERR "WARNING: open(%s): %s\n", $from, $!;
		return;
	}
	if (! open(TO, ">$to")) {
		printf STDERR "WARNING: create(%s): %s\n", $to, $!;
		return;
	}
	while (<FROM>) {
		print TO $_;
	}
	close(FROM);
	close(TO);
}

#
# main
#

# Command line arguments.
require "getopts.pl";
&Getopts('P:p:a:') || &usage();
if ($opt_P ne "") {
	$opt_P =~ s/\s+//g;
	@protos = split(/,/, $opt_P);
}
$pkgdir = $opt_p;
$arch = $opt_a;
&usage() if ($#protos <= 0 || $pkgdir eq "" || $arch eq "");

open(CHK, "chkclasses -b. -c. -p$pkgdir -a$arch -lq |") || die;
while ($path = <CHK>) {
	chop($path);
	$fromproto = "";
	@updateprotos = ();
	foreach $proto (@protos) {
		$fpath = "$proto/$path";
		if (-f $fpath) {
			$fromproto = $proto;
			last
		}
		push(@updateprotos, $proto);
	}
	if ($fromproto eq "") {
		print STDERR "WARNING:  $path not found in any proto.\n";
		next;
	}
	next if ($#updateprotos < 0);
	foreach $uproto (@updateprotos) {
		print "Copying $path from $fromproto to $uproto ...\n";
		$upath = "$uproto/$path";
		&mkpath($upath);
		&copyfile($fpath, $upath);
	}
}
close(CHK);
exit 0;
