#!/usr/bin/perl

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

# RCS: $Id: fetchscript,v 1.1.1.1 2002/08/29 09:45:37 wbmc Exp $


#------------------------------------------------------------------------

require "/opt/nec/wbmc/lib/wbmc.pl";

#
# ᡼μ¹ԥץ
#

# å򤫤
if (!&lockFile("fetchmailrc.tmp", $WBMC_LOCK_W_NB, *LOCK)) {
	goto sendmail;
}
$lock_flag = 1;

# 
$fetchmailrc = "/etc/opt/nec/wbmc/fetchmailrc";
if (!&readFile($fetchmailrc, "fetchmailrc", *lines)) {
	goto sendmail;
}

$poll_flag = -1;
for ($i = 0; $i <= $#lines; $i++) {
	if (!$proto_flag && $lines[$i] =~ /^defaults\s+protocol\s+POP3/i) {
		unshift(@lines_tmp, $lines[$i]);
		$proto_flag = 1;
	}
	elsif ($lines[$i] =~ /^poll\s+([^\s]*)\s+([^\s]*)/i) {
		$mailsv = $1;
		$user = $2;
		if ($mailsv ne "") {
			push(@lines_tmp, $lines[$i]);
			if ($user ne "user") {
				$poll_flag = $#lines_tmp;
			}
		}
	}
	elsif ($poll_flag != -1 && $lines[$i] =~ /^user\s+/i) {
		push(@lines_tmp, $lines[$i]);
		$user_flag = 1;
	}
}
if (!$proto_flag) {
	unshift(@lines_tmp, "defaults protocol POP3\n");
}
if ($poll_flag != -1 && !$user_flag) {
	splice(@lines_tmp, $poll_flag, 1);
}

if ($#lines_tmp <= 0) {
	goto sendmail;
}

$fetchmailrc_tmp = "/etc/opt/nec/wbmc/fetchmailrc.tmp";
$tmp_file = "$fetchmailrc_tmp.$$";

# ȥե򥪡ץ󤷤ƽ񤭹
$old = umask(0177);
if (!open(OUT, "> $tmp_file")) {
	goto sendmail;
}
if (!print(OUT @lines_tmp)) {
	close(OUT);
	goto sendmail;
}
close(OUT);
umask($old);

# Υե˥͡ह
if (!rename($tmp_file, $fetchmailrc_tmp)) {
	goto sendmail; 
}   
 
# եΥ⡼ɤꤹ
if (chmod(0600, $fetchmailrc_tmp) != 1) {
	goto sendmail;
}

# ץХ᡼
system("/usr/bin/fetchmail -s -f $fetchmailrc_tmp 2>&1 | grep -v 'fetchmail: Unknown command: \"last\".'");

sendmail:

# SMTP ̾μ
$smtp = "";
@lines = ();
if (!&readFile("/etc/sendmail.cf", "sendmail.cf", *lines)) {
	goto done;
}
for ($i = 0; $i <= $#lines; $i++) {
	if ($lines[$i] =~ /DRsmtp:\[(.+)\]/) {
		$smtp = $1;
		last;
	}
}

# ץХإ᡼
if ($smtp ne "" && $smtp ne "relay.host.name") {
	system("/usr/sbin/sendmail -q");
}

done:

if ($lock_flag) {
	close(LOCK);
}

if (-e $tmp_file) {
	unlink($tmp_file);
}

if (-e $fetchmailrc_tmp) {
	unlink($fetchmailrc_tmp);
}

exit;
