#!/usr/bin/perl

BEGIN {
  use FindBin;
  use lib $FindBin::Bin;
}

use Getopt::Long;

use Modules::Apache::Config::VServer;
use strict;


Getopt::Long::Configure('require_order');

my @args_config = (
									 'input|i=s',
									 'special|s=s',
									 'output|o=s',
									 'delete|d',
									 'debug|dbg',
									 'help|h'
									);
my %args = ();
unless( &GetOptions( \%args, @args_config ) ){
	&printHelp();
	die( "Error: command line options\n" );
}

if( $args{'help'} ){
  &printHelp;
  exit 0;
}

my $special = shift @ARGV || $args{'special'};
my $input = shift @ARGV || $args{'input'};
my $output = shift @ARGV || $args{'output'};

unless( defined  $special ){
	&printHelp();
	die( "Error: no httpd special specified\n" );
}

my $vs = new Modules::Apache::Config::VServer;

if( open( SPEC, '<', $special ) ){
	my $text = join( '', <SPEC> );
	$text =~ s/\r//g;
	$text =~ s/##domain##/domain.confixx.com/g;
	$text =~ s/##user##/web0/g;

	$vs->prepSpecial( $text );
	close( SPEC );
}else{
	die( "Error: open file '$special': $!\n" );
}

if( $input ){
	open( INPUT, '<', $input ) or
		die "Error: can't open file '$input': $!\n";
}else{
	open( INPUT, "<&STDIN" ) or
		die "Error: can't dup STDIN: $!\n";
}

$vs->appendText( <INPUT> );

if( $input ){
	close( INPUT );
}

my( $old_stdout );
if( $output ){
	open( OUTPUT, '>', $output ) or
		die "Error: can't open file '$output': $!\n";
	$old_stdout = select( OUTPUT );
}

$vs->applyReplace();

map{
	print $_, "\n";
} @{$vs->text} if ref( $vs->text ) =~ /ARRAY/;

print $vs->zusatz, "\n</VirtualHost>\n";


if( $output ){
  close( OUTPUT );
  select( $old_stdout ) ;
}

if( exists $args{'delete'} ){
#
# clean work files
#
	if( $input && -f $input ){
		unlink $input;
	}
	if( $special && -f $special ){
		unlink $special;
	}
	if( $output && -f $output ){
		unlink $output;
	}
}

exit 0;

sub printHelp{

	print STDERR <<"END_HELP";

test_httpd_special.pl - test how works httpd specail

parameters: <special> [input] [output]
   --input   | -i <path>
   --output  | -o <path>
   --special | -s <path>

   --help    | -h 
   --delete  | -d         delete files ufter test

END_HELP
 
}
