2006-09-21 [wwp] 2.4.0cvs204
[claws.git] / tools / fix_date.sh
1 #!/bin/sh
2
3 # usage: fix_date.sh <filename> [<filename>..]
4 # It will replace the Date: value w/ the one picked up from more recent
5 # Received: field if this field resides in one line. Otherwise, it will
6 # take the file modification time (using a RFC 2822-compliant form).
7 # If no X-Original-Date already exist, the former Date value will be set
8 # in such field.
9
10 if [ $# -lt 1 ]
11 then
12         echo "usage: ${0##*/} <filename> [<filename> ..]"
13         exit 1
14 fi
15
16 TMP="/tmp/${0##*/}.tmp"
17 while [ -n "$1" ]
18 do
19         test ! -s "$1" && \
20                 continue
21
22         X_ORIGINAL_DATE=$(grep -Eim 1 '^X-Original-Date: ' "$1" | cut -d ':' -f 2)
23         DATE=$(grep -Eim 1 '^Date: ' "$1" | cut -d ':' -f 2)
24         RECEIVED_DATE=$(grep -Eim 1 ';( (Mon|Tue|Wed|Thu|Fri|Sat|Sun),)? [0-9]+ (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dev) [0-9]+ [0-9]+:[0-9]+:[0-9}+ [-+][0-9]+' "$1" | cut -d ';' -f 2)
25 # strict, day of week needed
26 #       RECEIVED_DATE=$(grep -Eim 1 '; (Mon|Tue|Wed|Thu|Fri|Sat|Sun), [0-9]+ (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dev) [0-9]+ [0-9]+:[0-9]+:[0-9}+ [-+][0-9]+' "$1" | cut -d ';' -f 2)
27         FILE_DATE=$(ls -l --time-style="+%a, %d %b %Y %X %z" "$1" | tr -s ' ' ' ' | cut -d ' ' -f 6-11)
28         # we could also use the system date as a possible replacement
29         #SYSTEM_DATE="$(date -R)"
30
31         # determine which replacement date to use
32         if [ -z "$RECEIVED_DATE" ]
33         then
34                 # don't forget to add the leading whitespace
35                 REPLACEMENT_DATE=" $FILE_DATE"
36         else
37                 REPLACEMENT_DATE="$RECEIVED_DATE"
38         fi
39
40         # ensure that a X-Original-Date is set
41         if [ -z "$X_ORIGINAL_DATE" ]
42         then
43                 test -z "$DATE" && \
44                         echo "X-Original-Date:$REPLACEMENT_DATE" > "$TMP" || \
45                         echo "X-Original-Date:$DATE" > "$TMP"
46         else
47                 :> "$TMP"
48         fi
49
50         # replace/set the date and write all lines
51         if [ -z "$DATE" ]
52         then
53                 echo "Date:$REPLACEMENT_DATE" >> "$TMP"
54                 cat "$1" >> "$TMP"
55         else
56                 sed "s/^Date: .*/Date:$REPLACEMENT_DATE/" "$1" >> "$TMP"
57         fi
58
59         # uncomment the following line to backup the original file
60         #mv -f "$1" "$1.bak"
61
62         mv -f "$TMP" "$1"
63         if [ $? -ne 0 ]
64         then
65                 echo "error while moving $TMP to $1"
66                 exit 1
67         fi
68
69         shift
70 done
71 exit 0