#!/usr/bin/perl
#
#ARGV[0]:インストールディレクトリ 
#ARGV[1]: 0 追加 (add)
#ARGV[1]: 1 削除 (del)　
#
use File::Copy;
use Cwd;
use FindBin qw($Bin);
my $current_dir = $Bin;
my $mode="add";

if ( scalar @ARGV < 2 ) {
	if ( $#ARGV < 1  ) {
		print "$0 :need argument of WitchyMail installed directory\n\n";
		&PrintSynonym;
		exit;
	}
}

#$wmdir = "\"" . $ARGV[0] . "\"";
#$wmuser = $ARGV[1]; #ユーザ名 
my $wmuser; #ユーザ名 
my $wmdir;
my $wmsconf;
if ( scalar @ARGV >= 2 ) {
	$wmdir = $ARGV[0];  #インストールディレクトリ
	$wmsconf = "$wmdir" . "/WMS-current/etc/wms.conf";
	if ($ARGV[1] eq "add" or $ARGV[1] eq 0){
		$mode="add";
	}
	elsif ( $ARGV[1] eq "del" or $ARGV[1] eq 1){
		$mode="del";
	}
}
print "mode $mode\n";
$installed_path = "$wmdir";
$wms_current_dir="$installed_path"."/WMS-current";

$wmsap_l="local3.*                                                /var/log/wmsap.log\n";
$wmssys_l="local2.*                                                /var/log/wmssys.log\n";

@schflag = ( 0, 0 );


#ここまでにバッチ設定を取得する


#tmpに書き出し処理
#ユーザ名で置き換えが必要
#open(FHIN, "/var/spool/cron/$wmuser");
#open(FHOUT, ">/tmp/.witchy_cron") or die;

open(FHIN, "</etc/syslog.conf") or die;
open(FHOUT, ">/tmp/.witchy_syslog.conf") or die;
@list = <FHIN>;

foreach $data_line(@list){
#  print $data_line;
	  if ( $data_line =~ /\/var\/log\/wmssys\.log$/ ) {
			#設定追加時
			#if($ARGV[1] eq 0){
			if($mode eq "add"){
				print FHOUT "$wmssys_l";
				$schflag[0]=1;
			}
			next;	
		}
	  elsif ( $data_line =~ /\/var\/log\/wmsap\.log$/ ) {
			#設定追加時
			#if($ARGV[1] eq 0){
			if($mode eq "add"){
				print FHOUT "$wmsap_l";
				$schflag[1]=1;
			}
			next;	
		}
		else {
	  ##内容をそのままに
	  	print FHOUT $data_line;
		}	
}

#設定追加時
#if($ARGV[1] eq 0){
if($mode eq "add"){
	for ( 0..1 ) {
 	 if ( $_  eq  0 && $schflag[$_]  eq  0 ) {
			print FHOUT "$wmssys_l";
		}
 	 if ( $_  eq  1 && $schflag[$_]  eq  0 ) {
			print FHOUT "$wmsap_l";
		}
	}
}

close(FHIN);
close(FHOUT);

copy ("/tmp/.witchy_syslog.conf", "$wms_current_dir/etc/syslog.conf");
move ("/tmp/.witchy_syslog.conf", "/etc/syslog.conf");

open(FHIN, "/etc/syslog.conf") or die;
print "次のようにsyslog設定を書き出しました。/etc/syslog.conf\n";
@list = <FHIN>;
foreach $data_line(@list){
  print $data_line;
}

sub PrintSynonym(){
	print << "HERE";
usage: $0 DIR 

DESCRIPTION
    "DIR" is WitchyMail installed directory. (ex. /home/witchymail/wm_current )

HERE
}
