#!/usr/bin/perl

# Copyright (C) 2000-2005 NEC Corporation
# All Rights Reserved.

# RCS: $Id: tape_backup,v 1.1 2006/12/22 05:33:58 shodai Exp $
## 20041005 v6.0.1 -s オプション指定時 stdout/stderr を sjis 出力 oyama
## 20041028 v6.0.1 StarDefence対応 oyama
## 20051011 v6.0.8 StarDefence のディレクトリ(/home/local)を除外 oyama
## 20070129 v7.0.1 StarDefence対応処理の削除 sakai

#
# テープ バックアップ コマンド
#
# usage: tape_backup [-c conffilename] [-l] [-m]
#        -c     コンフィグレーションファイル
#        -l     メッセージをログに出力
#        -l無し メッセージをSTDERRに出力
#        -m     実行メッセージを出力
#        -s     mail用のメッセージを出す                ## 021009
#
# 戻り値: 成功:0
#         失敗:1
#

require "/opt/nec/wbmc/lib/wbmc.pl";
require join ("/", $WBMC_ADM_DIR, "service/11sendmail/fml", "fml.pl");

use utf8;
use encoding 'utf8', Filter=>1;
use Encode;

$| = 1;
$old = select(STDERR); $| = 1; select($old);

##############################################################################
# 変数の初期化

$conf_file = "$WBMC_CONF_DIR/tape_backup.conf";	# app 4.1 rep
$conf_lock = "tape_backup.conf";				# app 4.1 rep
$conf_file_tmp = "tape_backup.tmp";				# app 4.1 add
$tag_name  = "tape_backup";
$log_file  = "/var/log/wbmc";

$domain_conf      = "$WBMC_CONF_DIR/domain.conf";
$domain_conf_lock = "domain.conf";

$info_file = "tape_backup.info";
$info_lock = "tape_backup.lock";

$cluster_type = &cluster_typechk();			# 010426 add
$cluster_master = &cluster_masterchk();		# 010426 add

##############################################################################
# 引数処理

$argerr    = 0;
$argerrmsg = "";
$errtolog  = 0; # 0:STDERR, 1:LOG 
$msgout    = 0;
$tar_status = 0;	## 001227

for ($i = 0; $i < @ARGV; $i++) {
	if ($ARGV[$i] eq "-c") {
		if ($i == $#ARGV) {
			$argerrmsg = "'$ARGV[$i]'";
			$argerr = 1;
			next;
		}
		$conf_file = $ARGV[$i + 1];
		$i++;
	} elsif ($ARGV[$i] eq "-l") {
		$errtolog = 1;
	} elsif ($ARGV[$i] eq "-m") {
		$msgout = 1;
        } elsif ($ARGV[$i] eq "-s") {
                $send_mail_flg = 1;
#		binmode(STDOUT, ':encoding(7bit-jis)');
#		binmode(STDERR, ':encoding(7bit-jis)');
	} else {
		$argerrmsg = "'$ARGV[$i]'";
		$argerr = 1;
	}
}
if ( $send_mail_flg != 1 ){
#	binmode(STDOUT, ':encoding(euc-jp)');
#	binmode(STDERR, ':encoding(euc-jp)');
}
if ($send_mail_flg == 1) {print("バックアップ開始\n");}
if ($argerr) {
	&writeError("invalid argment $argerrmsg", "");
        if ($send_mail_flg == 1) {print("invalid argment $argerrmsg\n");}
        if ($send_mail_flg == 1) {print("バックアップに失敗しました。\n");}
	exit(1);
}

# サーバ形態対応	001222
if (!($workmode = &getConfParam("WbMC", "WorkMode"))) {
	&writeError("read file error INITCONF.INI", "");
        if ($send_mail_flg == 1) {print("read file error INITCONF.INI\n");}
        if ($send_mail_flg == 1) {print("バックアップに失敗しました。\n");}
	exit(1);
}

##############################################################################
# バックアップ情報ファイルからバックアップ情報を読み込む

print "バックアップ中：\n";

$item_flag        = 0;
$device           = "/dev/nst0";
$item             = "";
$target_dir       = "";
$backupmode       = "";
@line             = ();
$domainbackuptype = "";
$domainname       = "";
@domainlist       = ();
$fmlbackuptype    = "";
$fmlname          = "";
@fmllist          = ();

if (!&readFile($conf_file, $conf_lock, *tmp)) {
	&writeError("read file error '$conf_file'", "");
        if ($send_mail_flg == 1) {print("read file error '$conf_file'\n");}
        if ($send_mail_flg == 1) {print("バックアップに失敗しました。\n");}
	exit(1);
}

for ($i = 0; $i < @tmp; $i++) {
	if ($tmp[$i] =~ /\s*#/) {
		next;
	}
	if ($item_flag == 0) {
		if ($tmp[$i] =~ /^(.*)\s*{\s*$/) {
			$item = $1;
			$item =~ s/^\s*//;
			$item =~ s/\s*$//;
			$item_flag = 1;
		} elsif ($tmp[$i] =~ /^\s*DEVICE\s*=\s*(.*)\s*$/) {
			$device = &getValue($1);
			# テープの巻き戻し
			print "\n------ Rewind TAPE($device) -----\n";
			if (system("/bin/mt -f $device rewind")) {
				&writeError("mt rewind error", "");
                                if ($send_mail_flg == 1) {print("mt rewind error\n");}
                                if ($send_mail_flg == 1) {print("バックアップに失敗しました。\n");}
				exit(1);
			}
			# バックアップ情報ファイルのコピー
#			@path = split(/\//, $conf_file);						# app 4.1 del
#			if (system("/bin/cp -f $conf_file $path[@path-1]")) {	# app 4.1 del
			if (system("/bin/cp -f $conf_file $conf_file_tmp")) {	# app 4.1 rep
				&writeError("cp error '$conf_file'", "");
                                if ($send_mail_flg == 1) {print("cp error '$conf_file'\n");}
                                if ($send_mail_flg == 1) {print("バックアップに失敗しました。\n");}
				exit(1);
			}

			# app 4.1 add kokokara
			# バックアップ日付を保存 (スケジュール用のため)
			if (!&readFile($conf_file_tmp, $conf_file_tmp, *conf_tmp)) {
				&writeError("read file error '$conf_file_tmp'", "");
                                if ($send_mail_flg == 1) {print("read file error '$conf_file_tmp'\n");}
                                if ($send_mail_flg == 1) {print("バックアップに失敗しました。\n");}
				exit(1);
			}
			($sec,$min,$hour,$mday,$mon,$year) = localtime();
			$b_date = sprintf("%04d/%02d/%02d %02d:%02d:%02d",
				$year + 1900, $mon + 1, $mday, $hour, $min, $sec);
			$item_flag_tmp = 0;
			for ($j = 0; $j < @conf_tmp; $j++) {
				if ($conf_tmp[$j] =~ /^(.*)\s*{\s*$/) {
					$item_flag_tmp = 1;
				}
				if ($item_flag_tmp && $conf_tmp[$j] =~ /^\s*}\s*$/) {
					$item_flag_tmp = 0;
				}
				if ($item_flag_tmp == 0 && $conf_tmp[$j] =~ /^\s*DATE\s*=\s*(.*)\s*$/) {
					$conf_tmp[$j] = "DATE=$b_date\n";
					last;
				}
			}
			if (!&writeFile($conf_file_tmp, $conf_file_tmp, @conf_tmp)) {
				&writeError("write file error '$conf_file_tmp'", "");
                                if ($send_mail_flg == 1) {print("write file error '$conf_file_tmp'\n");}
                                if ($send_mail_flg == 1) {print("バックアップに失敗しました。\n");}
				exit(1);
			}
			# app 4.1 add kokomade

			# テープデバイス状態のチェック		## wbmc03-B17
			&checkTapeDevice();					## wbmc03-B17

			# バックアップ情報ファイルの書き込み
# delete -P option 001202 seki
# wbmc03-B17 update kokokara
#			if (system("/bin/tar cfz $device --ignore-failed-read $path[@path-1]")) {
#				&writeError("tar write error", "$conf_file");
#				exit(1);
#			}
# update /bin/tar -> /opt/nec/baktar/baktar 001227
#			open(CMD, "/opt/nec/baktar/baktar cfz $device --ignore-failed-read $path[@path-1] 2>&1 |");	# app 4.1 del
			open(CMD, "/opt/nec/baktar/baktar cfz $device --ignore-failed-read $conf_file_tmp 2>&1 |");	# app 4.1 rep
			$errmessage = "";
			while (<CMD>) {
				if (/\/opt\/nec\/baktar\/baktar/) {		# 001227
					if (/Removing leading/i) {
						next;
					}
					if (/Archive contains future timestamp/i) {
						next;
					}
			        # tarメッセージを赤文字で表示		001222
                                        if($send_mail_flg != 1) {
					    print "<FONT COLOR=red>$_</FONT>";
                                        }
					$errmessage = $_;
				}
			}
			close(CMD);
			if ($? || $errmessage) {			## 001222
				if ($errmessage eq "") {
					&writeError("tar write error", "$conf_file");
                                        if ($send_mail_flg == 1) {print("tar write error\n");}
                                        if ($send_mail_flg == 1) {print("バックアップに失敗しました。\n");}
					exit(1);
				} else {
					&writeError($errmessage, "$conf_file");
                                        if ($send_mail_flg == 1) {print("$errmessage\n");}
                                        if ($send_mail_flg == 1) {print("バックアップに失敗しました。\n");}
					exit(1);
				}
			}
# wbmc03-B17 update kokomade
			# バックアップ情報ファイルの削除
#			unlink($path[@path-1]);		# app 4.1 del
			unlink($conf_file_tmp);		# app 4.1 rep
		}
	} else {
		if ($tmp[$i] =~ /^\s*\}\s*$/) {
			# バックアップの実行
			if (&doBackup()) {
				exit(1);
			}
			$item             = "";
			$name             = "";		# 010426 add
			$target_dir       = "";
			$backupmode       = "";
			@line             = ();
			$domainbackuptype = "";
			$domainname       = "";
			@domainlist       = ();
			$item_flag        = 0;
			$fmlbackuptype    = "";
			$fmlname          = "";
			@fmllist          = ();
			$spool            = "";
			$pre_backup       = "";
			$post_backup      = "";
		} elsif ($tmp[$i] =~ /^\s*TARGET\s*=\s*(.*)\s*$/) {
			$target_dir = &getValue($1);
		} elsif ($tmp[$i] =~ /^\s*BACKUPMODE\s*=\s*(.*)\s*$/) {
			$backupmode = &getValue($1);
			@line = split(/\s+/, $backupmode);
		} elsif ($tmp[$i] =~ /^\s*DOMAINBACKUPTYPE\s*=\s*(.*)\s*$/) {
			$domainbackuptype = &getValue($1);
		} elsif ($tmp[$i] =~ /^\s*DOMAINNAME\s*=\s*(.*)\s*$/) {
			$domainname = &getValue($1);
			@domainlist = split(/\s+/, $domainname);
		} elsif ($tmp[$i] =~ /^\s*FMLBACKUPTYPE\s*=\s*(.*)\s*$/) {
			$fmlbackuptype = &getValue($1);
		} elsif ($tmp[$i] =~ /^\s*FMLNAME\s*=\s*(.*)\s*$/) {
			$fmlname = &getValue($1);
			@fmllist = split(/\s+/, $fmlname);
		} elsif ($tmp[$i] =~ /^\s*SPOOL\s*=\s*(.*)\s*$/) {
			$spool = &getValue($1);
		# 010426 kokokara
		} elsif ($tmp[$i] =~ /^\s*SYMLINK\s*=\s*(.*)\s*$/) {
			$cluster_symlink = &getValue($1);
			@symlinklist = split(/\s+/, $cluster_symlink);
		} elsif ($tmp[$i] =~ /^\s*NAME\s*=\s*(.*)\s*$/) {
			$name = &getValue($1);
		} elsif ($tmp[$i] =~ /^\s*PRE_BACKUP\s*=\s*"(.*)"\s*$/) {
			$pre_backup = &getValue($1);
		} elsif ($tmp[$i] =~ /^\s*POST_BACKUP\s*=\s*"(.*)"\s*$/) {
			$post_backup = &getValue($1);
	        }
		# 010426 kokomade
	}
}

# セクション情報の書き込み
if (&writeSectionInfo("END")) {
	exit(1);
}

## 正常終了			001227
if ($tar_status == 0) {
	exit(0);
} else {
	exit(2);
}

##############################################################################
# テープデバイス状態のチェック

sub checkTapeDevice {
	while (1) {
		# テープデバイス状態の取得
		open(CMD, "/bin/mt -f $device status 2>&1 |");
		while (<CMD>) {
			if (/ONLINE/) {
				close(CMD);
				return;
			}
		}
		close(CMD);
		sleep(1);
	}
}

##############################################################################
# セクション情報の書き込み

sub writeSectionInfo {
	# セクション情報ファイルの作成
	$section[0] = $_[0];
	if (!&writeFile($info_file, $info_lock, @section)) {
		&writeError("write file error '$info_file'", "");
                if ($send_mail_flg == 1) {print("write file error '$info_file'\n");}
                if ($send_mail_flg == 1) {print("バックアップに失敗しました。\n");}
		return(1);
	}

	# テープデバイス状態のチェック
	&checkTapeDevice();

	# セクション情報ファイルの書き込み
# delete -P option 001202 seki
# wbmc03-B17 update kokokara
#	if (system("/bin/tar cfz $device --ignore-failed-read $info_file")) {
#		&writeError("tar write error", "$info_file");
#		return(1);
#	}
# update /bin/tar -> /opt/nec/baktar/baktar 001227
	open(CMD, "/opt/nec/baktar/baktar cfz $device --ignore-failed-read $info_file 2>&1 |");
	$errmessage = "";
	while (<CMD>) {
		if (/\/opt\/nec\/baktar\/baktar/) {		# 001227
			if (/Removing leading/i) {
				next;
			}
			if (/Archive contains future timestamp/i) {
				next;
			}
	        # tarメッセージを赤文字で表示		001222
                        if ($send_mail_flg != 1) {
			    print "<FONT COLOR=red>$_</FONT>";
                        }
			$errmessage = $_;
		}
	}
	close(CMD);
	if ($? || $errmessage) {			## 001222
		if ($errmessage eq "") {
			&writeError("tar write error", "$info_file");
                        if ($send_mail_flg == 1) {print("tar write error\n");}
                        if ($send_mail_flg == 1) {print("バックアップに失敗しました。\n");}
			return(1);
		} else {
			&writeError($errmessage, "$info_file");
                        if ($send_mail_flg == 1) {print("$errmessage\n");}
                        if ($send_mail_flg == 1) {print("バックアップに失敗しました。\n");}
			return(1);
		}
	}
# wbmc03-B17 update kokomade

	# セクション情報ファイルの削除
	unlink($info_file);

	return(0);
}

##############################################################################
# バックアップの実行

sub doBackup {
#	$cluster_type = &cluster_typechk();		010426 del
	# バックアップ対象のディレクトリが存在しない場合は終了
	if ($target_dir eq "") {
		&writeError("no target", $item);
                if ($send_mail_flg == 1) {print("no target\n");}
                if ($send_mail_flg == 1) {print("バックアップに失敗しました。\n");}
		return(1);
	}

	# ドメイン対応:ドメインコンフィグから読み込む
	if ($item eq "home" || $item eq "mail") {

		if ($domainbackuptype eq "ALL") {
			@domainlist = ();
			if (!&readFile($domain_conf, $domain_conf_lock, *conf)) {
				&writeError("read file error 'domain_conf'", "$item");
                                if ($send_mail_flg == 1) {print("read file error 'domain_conf'\n");}
                                if ($send_mail_flg == 1) {print("バックアップに失敗しました。\n");}
				return(1);
			}
			# ドメイン名取得
			$get_flg = 0;
			for ($ii = 0; $ii < @conf; $ii++) {
				if ($conf[$ii] =~ /^\s*#/) {
					next;
				}

				if ($conf[$ii] =~ /^\s*<DOMAINNAME\s*(.*)>\s*$/) {
					$domainname = $1;
					$domainname =~ s/\s*$//;
					$domainname =~ s/^\s*//;
					$get_flg = 1;
				} elsif ($get_flg && ($conf[$ii] =~ /^\s*<\/DOMAINNAME\s*>\s*$/ ||			## 001222
						 			 ($conf[$ii] =~ /^\s+/ && $WBMC_MGRVER =~ /^1\./ && $WBMC_MGRNAME =~ /Management Console for Appliance Server/))) {	## 001222
					$get_flg = 0;
					if (($domain_mode eq "REAL")&&($cluster_type)) {
						next;
					}
					if ($item eq "home") {
						# ドメイン作成
						push(@domainlist, $domainname);
					}
					if ($item eq "mail" && $mail eq "on") {
						# ドメイン作成
						push(@domainlist, $domainname);
					}
				} elsif ($get_flg && $conf[$ii] =~ /^\s*MODE\s*(.*)\s*$/) {
					$domain_mode = $1;
					$domain_mode =~ s/\s*$//;
					$domain_mode =~ s/^\s*//;
				} elsif ($get_flg && $conf[$ii] =~ /^\s*MAIL_SERVICE\s*(.*)\s*$/) {
					$mail = $1;
					$mail =~ s/\s*$//;
					$mail =~ s/^\s*//;
				}
			}
		}

		$domaincnt = @domainlist;

		if ($item eq "mail") {
			@target_dir_list = ();
			@target_dir_list = split(/\s+/, $target_dir);
			$target_dir_master = $target_dir_list[0];
			$target_dir_spool = "";
			for ($ii = 1; $ii < @target_dir_list; $ii++) {
				$target_dir_spool .= " $target_dir_list[$ii]";
			}
			if ($spool) {
				$domaincnt++;
			}
		} else {
			$target_dir_master = $target_dir;
		}

		if ($domaincnt eq 0) {
			&writeError("no target domain", "$item");
                        if ($send_mail_flg == 1) {print("no target domain\n");}
                        if ($send_mail_flg == 1) {print("バックアップに失敗しました。\n");}
			return(1);
		}
	} elsif ($item eq "fml") {
		# メーリングリスト対応
		if ($fmlbackuptype eq "ALL") {
			@fmllist = ();
#			&getListName(*fmlname);
			@fmlname = &getAllDomainName();
			for ($ii = 0; $ii < @fmlname; $ii++) {
				push(@fmllist, $fmlname[$ii]);
			}
		}
		$domaincnt = @fmllist;
		@domainlist = @fmllist;						# 010426 add
		$target_dir_master = $target_dir;
		if ($domaincnt eq 0) {
			&writeError("no target fml", "$item");
                        if ($send_mail_flg == 1) {print("no target fml\n");}
                        if ($send_mail_flg == 1) {print("バックアップに失敗しました。\n");}
			return(1);
		}
	} elsif ($item eq "sysconf") {
#		$target_dir_master = $target_dir;			# 010426 del
		$domaincnt = 1;
	} else {
		$domaincnt = 1;
	}

	# ターゲットが存在するかチェック	010426 add
	if ($item eq "sysconf" || $item eq "conf" || $item eq "log") {
		$target_dir =~ s/[\s,]+/ /g;
		@target_dir_chk = split(/ /, $target_dir);
		$target_dir = "";
		for($ii = 0; $ii < @target_dir_chk; $ii++) {
			$dir_chk = $target_dir_chk[$ii];
			$dir_chk =~ s/\*//;
			if (-e $dir_chk) {
				$target_dir .= " $target_dir_chk[$ii]";
			}
		}
	}

	# CLUSTERPRO Lite! 対応で /etc/clusterpro は対象外		010510 add
	if (-e "/etc/clusterpro") {
		if ($item eq "sysconf" || $item eq "conf") {
			# ディレクトリの一覧を得る
			if (!opendir(DIR, "/etc")) {
				&writeError("no directory", "$item");
                                if ($send_mail_flg == 1) {print("no directory\n");}
                                if ($send_mail_flg == 1) {print("バックアップに失敗しました。\n");}
				exit(1);
			}
			@dirs = readdir(DIR);
			closedir(DIR);
			@dirs = sort(@dirs);
			$target_etcdir = "";
			foreach $dir (@dirs) {
				if (($dir eq ".") || ($dir eq "..")) {
					next;
				}
				if ($dir =~ /clusterpro/){
					next;
				}
				$target_etcdir .= " /etc/$dir";
			}
			$target_dir =~ s/\/etc /$target_etcdir /;
		}
	}

	# バックアップ方式毎のドメイン毎
#	for ($j = 0; $j < @line; $j++) {		# 010426 del
#		$backupmode = $line[$j];			# 010426 del
		for ($k = 0; $k < $domaincnt; $k++) {

			# セクション情報の書き込み
			# 010426 kokokara
			if ($item eq "home" || $item eq "mail" || $item eq "fml") {
				if ($domainlist[$k] ne "") {
					if ($item eq "fml") {
						if (&writeSectionInfo("FML=$domainlist[$k]\n$name($domainlist[$k])\n$target_dir_master\n${item}_${domainlist[$k]}\n$cluster_symlink")) {
							return(1);
						}
					} else {
						if (&writeSectionInfo("ITEM=$item\n$name($domainlist[$k])\n$target_dir_master\n${item}_${domainlist[$k]}\n$cluster_symlink")) {
							return(1);
						}
					}
				} else {
					if (&writeSectionInfo("ITEM=$item\n$name(システムスプール)\n$target_dir_spool\n${item}_spool\n$cluster_symlink")) {
						return(1);
					}
				}
			} else {
				if (&writeSectionInfo("ITEM=$item\n$name\n$target_dir\n$item\n$cluster_symlink")) {
					return(1);
				}
			}
			# 010426 kokomade

			# 001222 kokokara
			$mode = "";
			$hostname = "";
			if ($WBMC_MGRVER =~ /^1\./ && ($item eq "home" || $item eq "mail") && $WBMC_MGRNAME =~ /Management Console for Appliance Server/) {
				if (!&GetDomainParam($domainlist[$k], "MODE", *mode)) {
					&writeError("cannot read file MODE", "$item");
                                        if ($send_mail_flg == 1) {print("cannot read file MODE\n");}
                                        if ($send_mail_flg == 1) {print("バックアップに失敗しました。\n");}
					exit(1);
				}
				if (!&GetDomainParam($domainlist[$k], "HOSTNAME", *hostname)) {
					&writeError("cannot read file HOSTNAME", "$item");
                                        if ($send_mail_flg == 1) {print("cannot read file HOSTNAME\n");}
                                        if ($send_mail_flg == 1) {print("バックアップに失敗しました。\n");}
					exit(1);
				}
			}
			# 001222 kokomade

			# 010426 kokokara
			## フェイルオーバクラスタのマスタでのみ実行
			@symlink_dir_list = ();
			if ($cluster_type eq "cluster" && $cluster_master eq "master") {
				for($l = 0; $l < @symlinklist; $l++) {
					$chkdir = "$symlinklist[$l]";
					# /home/web
					if ($item eq "home") {
						$chkdir = "$symlinklist[$l]/$domainlist[$k]";
					}
					# /home/mail
					if ($item eq "mail") {
						# spool 限定 2 つめ
						if ($spool && $k eq @domainlist) {
							if ($l != 1) {
								next;
							}
						} else {
							if ($l > 0) {
								last;
							}
							$chkdir = "$symlinklist[$l]/$domainlist[$k]";
						}
					}
					@symlink_dir = ();
					if ($err = &chksymlink($chkdir, *symlink_dir)) {
						&writeError("$err", "$item");
                                                if ($send_mail_flg == 1) {print("$err\n");}
                                                if ($send_mail_flg == 1) {print("バックアップに失敗しました。\n");}
						exit(1);
					}
					for($ii = 0; $ii < @symlink_dir; $ii++) {
						if (&dupchksymlink($symlink_dir[$ii], @symlink_dir_list)) {
							if ($item eq "fml") {
								push(@symlink_dir_list, "$symlink_dir[$ii]/${fmllist[$k]}");
							} else {
								push(@symlink_dir_list, $symlink_dir[$ii]);
							}
						}
					}
				}
			}
			# 010426 kokomade

			# ドメイン用バックアップ対象ディレクトリ設定
			if ($item eq "home" || $item eq "mail") {
				# 実ディレクトリ対応
#				if (!&GetDomainParam($domainlist[$k], "MODE", *mode)) {		##001110
#					&writeError("cannot read file MODE", "$item");			##001110
#					return(1);												##001110
#				}															##001110
#				if (!&GetDomainParam($domainlist[$k], "HOSTNAME", *hostname)) {
#					&writeError("cannot read file HOSTNAME", "$item");
#					return(1);
#				}
#				if ($mode eq "REAL") {
#					$target_dir = "$target_dir_master/${hostname}.${domainlist[$k]}";
#				} else {
#					if (@symlink_dir_list eq 0) {			# 010426 del
#						$target_dir = "$target_dir_master/${domainlist[$k]}";	# 010426 del
						# 001222 kokokara
						if ($mode eq "REAL" && $WBMC_MGRVER =~ /^1\./ && $WBMC_MGRNAME =~ /Management Console for Appliance Server/) {
							$target_dir = "$target_dir_master/${hostname}.${domainlist[$k]}";
						} else {
							$target_dir = "$target_dir_master/${domainlist[$k]}";
						}
						# 001222 kokomade
#					} else {								# 010426 del
						# フェイルオーバクラスタ時
						for ($l = 0; $l < @symlink_dir_list; $l++) {
							$target_dir .= " $symlink_dir_list[$l]";				# 010426 rep
						}
#					}										# 010426 del
#				}
				if ($item eq "mail" && $spool && $k eq @domainlist) {
					$target_dir = $target_dir_spool;
					# 010426 kokokara
					# フェイルオーバクラスタ時
					for ($l = 0; $l < @symlink_dir_list; $l++) {
						$target_dir .= " $symlink_dir_list[$l]";
					}
					# 010426 kokomade
				}
			} elsif ($item eq "fml") {
				# 010426 kokokara
				if ($cluster_type eq "cluster") {
					$target_dir = "$target_dir_master";
				} else {
					$target_dir = "$target_dir_master/${fmllist[$k]}";
				}
				# フェイルオーバクラスタ時
				for ($l = 0; $l < @symlink_dir_list; $l++) {
					$target_dir .= " $symlink_dir_list[$l]";
				}
			} elsif ($item eq "conf" || $item eq "sysconf") {
				# フェイルオーバクラスタ時
				@slink_list = ();
				for ($l = 0; $l < @symlink_dir_list; $l++) {
					$target_dir .= " $symlink_dir_list[$l]";
					# slink 取得 or aquota.group or aqouta.user
					if ($item eq "sysconf") {
						if ($symlink_dir_list[$l] =~ /^(.*)\/.wbmc\/.wbmcsys\//	||
							$symlink_dir_list[$l] =~ /^(.*)\/web\//				||
							$symlink_dir_list[$l] =~ /^(.*)\/mail\//) {
							if (&dupchksymlink($1, @slink_list)) {
								push(@slink_list, $1);
								if (-f "$1/.wbmc/slink") {
									$target_dir .= " $1/.wbmc/slink";
								}
								if (-f "$1/aquota.group") {
									$target_dir .= " $1/aquota.group";
								}
								if (-f "$1/aquota.user") {
									$target_dir .= " $1/aquota.user";
								}
							}
						}
					}
				}
				# 010426 kokomade
			}

			# メーリングリスト対応：ロック
			if ($item eq "fml") {
#				if (&lockFml($fmllist[$k], $WBMC_LOCK_R_NB, *lockcf, *lockph)) {
				if (&lockDomainFml($fmllist[$k], $WBMC_LOCK_R_NB, *lockcf)) {
					&writeError("lockFml failed $fmllist[$k]", "$item");
                                        if ($send_mail_flg == 1) {print("lockFml failed $fmllist[$k]\n");}
                                        if ($send_mail_flg == 1) {print("バックアップに失敗しました。\n");}
					return(1);
				}
			}

			# テープデバイス状態のチェック
			&checkTapeDevice();

			# 引数に-mあり:メッセージは画面に表示
			#       -m無し:メッセージは表示しない

			# アーカイブ作成
			print "\n------ Start $item -----\n";
			# 001222 kokokara update
			# mailtar 存在チェック
			# mailtar コマンド	(システム全ファイル)
			#	appliance3.0 ～
			#	appliance2.0 MailServer	(Standalone/MailCluster) SEC (Standalone)
			# tar コマンド		(システム全ファイル)
			#	appliance2.0 WebServer	(Standalone/WebLoadbalance)
			$mailtar_flg = "off";
			if ($WBMC_MGRVER =~ /^1\./ && $WBMC_MGRNAME =~ /Management Console for Appliance Server/) {
				if (($workmode eq "Standalone" && $WBMC_MACHINE_TYPE eq "mail") ||
					 $workmode eq "MailCluster"	||
					 ($workmode eq "Standalone" && $WBMC_MACHINE_TYPE eq "pre")) {
					$mailtar_flg = "ok";
				}
			} else {
				$mailtar_flg = "ok";
			}
			# 001222 kokomade update

                        #2004/10/28 StarDefence対応 oyama
                        #2007/01/29 StarDefence対応処理の削除 sakai
#                        system("/etc/init.d/webdef stop");

                        if ($pre_backup ne "" ) {
                                &writeLog("exec \"$pre_backup\" before backup.", $tag_name, $log_file);
                                system("$pre_backup >/dev/null 2>&1");
                        }

			if ($item eq "mail" || ($item eq "sysconf" && $mailtar_flg eq "ok")) {
# delete -P option 001202 seki
# --exclude /home/local directory 051011 oyama
				$pid = open(CMD, "/opt/nec/mailtar/mailtar cvfz $device --ignore-failed-read --exclude-from=/etc/opt/nec/wbmc/exclude $target_dir 2>&1 |");
			} else {
# delete -P option 001202 seki
# update /bin/tar -> /opt/nec/baktar/baktar 001227
# --exclude /home/local directory 051011 oyama
				$pid = open(CMD, "/opt/nec/baktar/baktar cvfz $device --ignore-failed-read --exclude-from=/etc/opt/nec/wbmc/exclude $target_dir 2>&1 |");
			}

			# 001222 kokokara
			$newpage = "./tape_main.cgi?$item";
			$killmode = "tape";
                        if ($send_mail_flg == 1) {
                            print("バックアップ実行中\n");
                        }
                        else {
			    print "バックアップ実行中．．．<A HREF=\"./kill_pid2.cgi?$pid+$newpage+$killmode\">中断</A>\n";
                        }
			# 001222 kokomade

			# メーリングリスト対応：アンロック
			if ($item eq "fml") {
#				&unlockFml($lockcf, $lockph);
				&unlockDomainFml($lockcf);
			}

			$errmessage = "";
			$cnt = 1;
			while (<CMD>) {
				if (/\/opt\/nec\/baktar\/baktar: / || /\/opt\/nec\/mailtar\/mailtar: /) {	# wbmc03-B17 update	001227
					if (/Removing leading/i) {
						next;
					}
					if (/Archive contains future timestamp/i) {
						next;
					}
			        # tarメッセージを赤文字で表示		001222
                                        if ($send_mail_flg != 1) {
					    print "<BR><FONT COLOR=red>$_</FONT>";
                                        }
					$errmessage = $_;
				}
				if (/^baktar: / || /^mailtar: /) {							# wbmc03-B17 update	001227
					$errmessage = $_;
					last;
				}
				if ($msgout) {
					if (($cnt % 10) == 1) {
						print "o";
					}
					if (($cnt % 100) == 0) {
						print " $_";
					}
					$cnt++;
				}
			}
			if ($msgout) {
				if (($cnt % 100) > 0) {
					print " done\n";
				}
			}

			close(CMD);

                        if ($post_backup ne "" ) {
                                &writeLog("exec \"$post_backup\" after backup.", $tag_name, $log_file);
                                system("$post_backup >/dev/null 2>&1");
                        }

                        #2004/10/28 StarDefence対応 oyama
                        #2007/01/29 StarDefence対応処理の削除 sakai
#                        system("/etc/init.d/webdef start");

			if ($?) {
				if ($errmessage eq "") {
					&writeError("tar: Unknown error", $item);
                                        if ($send_mail_flg == 1) {print("tar: Unknown error\n");}
                                        if ($send_mail_flg == 1) {print("バックアップに失敗しました。\n");}
					return(1);
				} else {
					&writeError($errmessage, $item);
                                        if ($send_mail_flg == 1) {print("$errmessage\n");}
                                        if ($send_mail_flg == 1) {print("バックアップに失敗しました。\n");}
					return(1);
				}
			} elsif ($errmessage) {			## 001227
				$tar_status = 1;			## 001227
			}
		}
#	}				# 010426 del

	# 正常終了
        if ($send_mail_flg == 1) {print("バックアップが終了しました。");}
	return(0);
}

#-----------------------------------------------------------------------
sub writeError {
	local($msg, $item) = @_;

	$msg = decode('utf8', $msg);
	$msg =~ s/\s*$//;
	if ($item ne "") {
		$msg = "[$item]$msg";
	}
	if ($errtolog) {
		$msg = encode('utf8', $msg);
		&writeLog($msg, $tag_name, $log_file);
	} else {
		print STDERR "$tag_name:$msg\n";
	}
}

sub getValue {
	local($str) = @_;

	$str =~ s/^[\s]*//;
	$str =~ s/[\s]*$//;
	if ($str =~ /^"(.*)"$/) {
		$str = $1;
	}

	return($str);
}

# シンボリックリンク先を取得
sub chksymlink
{
	local($dirname,*symlink_dir) = @_;
	local(*DIR);
	my($i,$err,@lslist,@lsinfo);

	if (!opendir(DIR, "$dirname")) {
		$err = "not directory $dirname<BR>";
		return $err;
	}
	close(DIR);

	open(DIR, "/bin/ls -la $dirname |");
	@lslist = <DIR>;
	close(DIR);

	for ($i = 0; $i < @lslist; $i++) {
		@lsinfo = split(/\s+/, $lslist[$i]);
		if ($lsinfo[0] =~ /^l/) {
			push(@symlink_dir, $lsinfo[10]);
		}
	}
	return "";
}

sub dupchksymlink
{
	local($symlink,@list) = @_;
	my($i);

	for ($i = 0; $i < @list; $i++) {
		if ($list[$i] eq $symlink) {
			return 0;
		}
	}
	return 1;
}
