#!/usr/bin/perl
#
# freeze server side includes
#
$target = shift;

unless ( $target ) {
	print STDERR <<X;
current dir must be document root of site to freeze

usage: $0 <target directory> [ <files> <subdirs> ]
X
	exit;
}

chomp ($docroot = `pwd`);
&freeze($docroot, $target);
exit;

sub freeze {
	($root, $target) = @_;
	`mkdir $target`;
	require 'find.pl';
	&find(@ARGV);
}

sub wanted {
	#rint "### from $name to $root/$target/$name\n";
	#eturn 1 if /\.(inc|ssi|hti)$/i;	# do not copy ssi files
	return &copy($_, "$root/$target/$name") unless /\.html?$/i;

	$cnt = 0;
	open (I, $_) or die "cannot read $name";
	open (O, ">$root/$target/$name") or
	  die "cannot write $root/$target/$name";

	while(<I>) {
		$cnt +=
		  s/<!--#include\s+virtual="([^"]+)"\s?-->/&include($1)/gei;
		print O;
	}
	close I;
	close O;

	print "freeze $name: $cnt include directives\n";
	return 1;
}

sub include {
	local ($_, $t, $o) = @_;
	$_ = $root.$_ if m!^/!;
	$t = $/;
	undef $/;
	open(INC, $_) or die "cannot include $_";
	$o = <INC>;
	close INC;
	$/ = $t;
	return $o;
}

sub copy {
	local ($from, $to) = @_;
	if (-d $from) {
		`mkdir $to`;
		print "mkdir $name\n";
	} else {
		`cp $from $to`;
		print "copy $name\n";
	}
	return 1;
}

