start tidy makefile
[hband-tools.git] / root-tools / sendmail.cron
blob607669043d2d7de50ce1e3c9b6fde8c582644d41
1 #!/bin/bash
3 set -e
4 set -o pipefail
5 set -u
7 . /usr/lib/tool/bash-utils
9 basedir=/var/log/cron/user
10 timestamp=`date "+%F %T %z"`
12 cron_user=''
13 cron_job_cmd=''
14 cron_job_id=''
15 partial_cron_message=''
17 while read -r line
19 if [ "$line" = '' -o "$line" = $'\r' ]
20 then
21 # we are at the end of headers
23 if [ -z "$cron_user" -o -z "$cron_job_cmd" ]
24 then
25 errx -2 "Missing either 'To' or 'Subject' header."
28 message_body=`cat`
29 if [ "$message_body" = "" -o "$message_body" = $'\n' ]
30 then
31 continue
33 full_cron_message=$partial_cron_message$line$'\n'$message_body
34 unset message_body
36 cron_job=$cron_job_cmd
37 if [ -n "$cron_job_id" ]; then cron_job=$cron_job_id; fi
39 command_name_noslash=`echo "$cron_job" | sed -e 's@/@⁄@g'`
40 command_name_noslash=${command_name_noslash:0:255}
41 user_name_noslash=`echo "$cron_user" | sed -e 's@/@⁄@g'`
43 set +e
44 # let's see if the user can create her own directory
45 if [ ! -d "$basedir/$user_name_noslash" ]
46 then
47 install -o "$cron_user" -m 0750 -d "$basedir/$user_name_noslash"
49 # if it's still is not there, let's try this custom sudo rule
50 if [ ! -d "$basedir/$user_name_noslash" ]
51 then
52 sudo subst_sudo_user /usr/bin/install -o '$SUDO_USER' -m 0750 -d /var/log/cron/user/'$SUDO_USER'
54 set -e
55 # if we failed to create the directory,
56 # let's fail when we try to write to a file under it.
58 logfile=$basedir/$user_name_noslash/$command_name_noslash
59 echo "$full_cron_message" | sed -e 's!^!'"$timestamp\t"'!' >> "$logfile"
60 else
61 # we are reading the email headers
63 partial_cron_message=$partial_cron_message$line$'\n'
64 if [ "${line:0:3}" = To: ]
65 then
66 # assuming a single space before username, ie. "To: USERNAME"
67 cron_user=${line:4}
68 elif [ "${line:0:8}" = Subject: ]
69 then
70 # assuming the header like "Subject: Cron <user@host> command..."
71 cron_job_cmd=`echo "$line" | cut -d' ' -f4-`
72 # trim leading spaces and tabs
73 cron_job_cmd=${cron_job_cmd/#+( |$'\t')}
74 elif [[ $line =~ X-Cron-Env:\ \<CRONJOBID=(.+?)\> ]]
75 then
76 # record CRONJOBID if the user did set it
77 cron_job_id=${BASH_REMATCH[1]}
80 done