#!/bin/sh
# Extract last-changed date for SVN file, by default in ISO-8601 UTC format.
# The date is sent to stdout; nothing is sent in case of error.
#
# Usage:
#
#     $0 $1
#
#         Echo on stdout timestamp of form:
#             2019-06-12T06:09:51Z
#         Nothing is output on stdout in case of error.
#
#     $0 -t $1
#
#         If timestamp can be extracted without error,
#         and if not already extant then create timestamp of form $1.timestamp,
#         put the full UTC timestamp in it,
#         then set the timestamp of the timestampt file to match.
#
# $1 is file under SVN control for which last-changed date is required.
#

MAKETSFILE=false
if [ "-t" = "$1" ]; then
    MAKETSFILE=true
    shift
fi

LASTUPDATEDLTMP="`export TZ=UTC; svn info $1 | awk '/^Last Changed Date:/ && $6=="+0000" {print $4"T"$5"Z";exit}'`"

if [ "true" = "$MAKETSFILE" -a "" != "$LASTUPDATEDLTMP" ]; then
    TSFILE=$1.timestamp
    if [ ! -f "$TSFILE" ]; then
        # touch -t 202005031519 X
        TTS=`echo $LASTUPDATEDLTMP | awk -F'[-:TZ]' '{print $1$2$3$4$5"."$6}'`
        #echo "$LASTUPDATEDLTMP -> $TTS"
        # Create timestamp file.
        echo $LASTUPDATEDLTMP > $TSFILE
        touch -t $TTS $TSFILE
    fi
    # Don't output the timestamp.
    exit 0
fi


# By default output timstamp to stdout in UTC ISO 8061 format.
echo $LASTUPDATEDLTMP

exit 0



# Example usage:
% script/svn_last_changed.sh img/audio/clip1.mp3
2019-06-12T06:09:51Z


