summaryrefslogtreecommitdiff
path: root/Build-tools/logger.pm
blob: 835d8014aa0fc441a6a0482aa87064a8699b09d2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
# Helper functions

#
# Create a log entry
#
sub logger
{
	my $message=$_[0];
	print timestamp() . " " . $message . "\n" if $opt_verbose;
	if (defined $opt_log && !$opt_dry_run)
	{
		open LOG, ">>$LOGFILE" or die "Can't open logfile $LOGFILE!";
		print LOG timestamp() . " " . $message . "\n";
		close LOG;
	}
}

#
# run_command(<command>,<error message>)
# Execute the given command or die with the respective error message
# Just print out the command when doing a dry run
#
sub run_command
{
	my $command= $_[0];
	my $errormsg= $_[1];
	if ($opt_dry_run)
	{
		print "$command\n";
	}
	else
	{
		&logger($command);
		$command.= " >> $LOGFILE 2>&1" if defined $opt_log;
		$command.= " > /dev/null" if (!$opt_verbose && !$opt_log);
		system($command) == 0 or &abort("$errormsg\n");
	}
}

#
# abort(<message>)
# Exit with giving out the given error message or by sending
# it via email to the given mail address (including a log file snippet,
# if available)
#
sub abort
{
	my $message= $_[0];
	my $messagefile;
	$message= "ERROR: " . $message;
	&logger($message);

	if ($opt_mail && !$opt_dry_run)
	{
		$messagefile= "/tmp/message.$$";
		open(TMP,">$messagefile");
		print TMP "$message\n\n";
		close TMP;
		if (defined $opt_log)
		{
			system("tail -n 40 $LOGFILE >> $messagefile");
		}
		system("mail -s \"$subject\" $opt_mail < $messagefile");
		unlink($messagefile);
	}

	exit 1;
}

# Create a time stamp for logging purposes
sub timestamp
{
	return &ymd() . " " . &hms();
}

#
# return the current time as a string (HH:MM:SS)
#
sub hms
{
	my @ta= localtime(time());
	my $h= $ta[2];
	$h= "0" . "$h" if ($h <= 9);
	my $m= $ta[1];
	$m= "0" . "$m" if ($m <= 9);
	my $s= $ta[0];
	$s="0" . "$s" if ($s <= 9);

	return "$h:$m:$s";
}

#
# return the current date as a string (YYYYMMDD)
#
sub ymd
{
	my @ta=localtime(time());
	my $d=$ta[3];
	$d="0" . "$d" if ($d <= 9);
	my $m=$ta[4]+1;
	$m="0" . "$m" if ($m <= 9);
	my $y=1900+$ta[5];

	return "$y$m$d";
}