#!/bin/bash

# V 0.1.0 030815 timestamp_corr.sh
#
# Licensed under GPL
#
#  ¢  ¢ 
#  ¢ ¢
#  ¢     ¢¢  ¢  ¢  ¢¢   ¢¢     ¢¢   ¢¢   ¢¢
#  ¢ ¢  ¢  ¢ ¢  ¢ ¢  ¢ ¢  ¢   ¢  ¢ ¢  ¢ ¢  ¢
#  ¢  ¢ ¢     ¢¢  ¢  ¢  ¢¢¢ ¢  ¢¢  ¢     ¢¢¢
#                         ¢                ¢
#        martin         ¢¢     krung     ¢¢
#
# ++++++++++++++++++++++++++++++++++++++++++++++++
#
#  USAGE

#  copy the script into the directory containing 
#  the files to correct the timestamp.
#
#  REQUIRE
#  package atfs which contains utime



correction_day=1	# set the timestamp x day in the past


# loop over every file in directory

for file in $( ls . )
do
echo filename: $file

# read date out of file
datum=`stat -c %y $file`
echo timestamp: $datum

# extract day,month,year
day=${datum:8:2}
month=${datum:5:2}
year=${datum:0:4}


# new day

day=`expr $day - $correction_day`


# corrects day,month,year if there is
# a changeover in the month or year

if [ $day -eq 0 ]; then
  
  # find the previous month
  month=`expr $month - 1`  

  # if the month is 0 then it is dec 31 of
  # the previous year.
  if [ $month -eq 0 ]; then
    month=12
    day=31
    year=`expr $year - 1`  

  # if the month is not zero we need to find
  # the last day of the month
  else
    case $month in
      1|3|5|7|8|10|12) day=31;;
      4|6|9|11) day=30;;
      2)
        if [ `expr $year % 4` -eq 0 ]; then
          if [ `expr $year % 400` -eq 0 ]; then
            day=29
          elif [ `expr $year % 100` -eq 0 ]; then
            day=28
          else
            day=29
          fi
        else
          day=28
        fi
      ;;
    esac
  fi
fi


# echo $year $month $day 

datum=$year-$month-$day${datum:10:9}

echo timestamp minus $correction_day days: $datum

# converts the human readable date into days since 1970
epochalsec=`date -d "$datum" +%s`

echo epochalsec: $epochalsec	

# set the new timestamp

echo utime $epochalsec $epochalsec $file

`utime $epochalsec $epochalsec $file`

echo

done

