# Here are defined functions relating to dates, times and stamps:
#
#     ln_touch                RELATIVE-PATH-TO-EXISTING LINK
#     stamp_per_release       STAMP-FILE CTRL
#     epoch_per_stamp         STAMP-FILE
#     ddate_per_stamp         STAMP-FILE
#     month_per_stamp         STAMP-FILE
#     convert_format_ss_to_d2 DATE-IN-SNAPSHOT-FORMAT
#
# See 10function-definitions.bash for general notes that are relevant here.

# Using the syntax of ln(1), symbolically link, and then touch the symlink
# to match symlink's timestamp to that of its target. Example:
#
#     ln_touch existing foo/mylink
#
# The result is a new symlink foo/mylink that points to the existing
# file foo/existing and shares the latter's timestamp.
function ln_touch {
    local LNT_TARGET
    if [[ "$1" = /* ]]; then
        LNT_TARGET="$1"
    else
        LNT_TARGET="$(dirname -- "$2")/$1"
    fi
    ln -s$V -- "$1" "$2"
    touch -hr "$LNT_TARGET" -- "$2"
    return 0
}
readonly -f ln_touch

function stamp_per_release {
    touch -d "$(sed -rn -- 's/^Date:\s*//p;T;q' "$2")" "$1"
    return 0
}
readonly -f stamp_per_release

function epoch_per_stamp { stat -c%Y -- "$1"; return 0; }
readonly -f epoch_per_stamp

function ddate_per_stamp { stat -c%y -- "$1"; return 0; }
readonly -f ddate_per_stamp

function month_per_stamp {
    stat -c%y -- "$1"\
     | sed -r -- 's/^([[:digit:]]{4})-([[:digit:]]{2})-.*$/\1\2/'
    return 0
}
readonly -f month_per_stamp

# Return the date in a format the date(1) command can read. (It's
# called _d2 rather than _d because it is not the date command's
# canonical format.)
readonly F12_CFSSD_PAT1='^([[:digit:]]{8})T([[:digit:]]{2})'
readonly F12_CFSSD_PAT2='([[:digit:]]{2})([[:digit:]]{2})Z$'
readonly F12_CFSSD_PAT="${F12_CFSSD_PAT1}${F12_CFSSD_PAT2}"
function convert_format_ss_to_d2 {
    printf '%s' "$1"\
     | sed -r -- "s/${F12_CFSSD_PAT}/\\1 \\2:\\3:\\4 UTC/"
    return 0
}
readonly -f convert_format_ss_to_d2
true

