#!/bin/bash
name="hugo-timestamp"
version="1.0"
read -r -d '' help_message <<-EOF
Set a date/timestamp into a Hugo content files
Usage: hugo-timestamp [OPTIONS] TARGET DATETIME
Options:
-h, --help print this message and exit
-q, --quiet suppress error messages
-v, --verbose show additional messages
-V, --version print version number and exit
EOF
source /usr/local/lib/mylib.bash
. /usr/local/lib/myparse.bash
# error if no filenames given
if [[ ${#positional[@]} -lt 2 ]]; then
usage_msg
fi
_ed_append_date() {
ed -s "$1" <<EOF
/^title:
a
date: "$2"
.
w
q
EOF
}
_ed_overwrite_date() {
ed -s "$1" <<EOF
g/^date:/c
i
date: "$2"
.
w
q
EOF
}
filename="${positional[0]}"
newdate="${positional[1]}"
# if filename does not exist
if [[ ! -f "$filename" ]]; then
error_msg "No such file '$filename'"
# main routine
else
# try read timestamp from file
olddate="$(hugo-extract-timestamp "$filename")"
# branch 1: has no timestamp so append one
if [[ -z "$olddate" ]]; then
if [[ "$verbose" -eq 1 ]]; then
debug_msg "No date found, creating one"
fi
_ed_append_date "$filename" "$newdate"
# branch 2: has a timestamp so replace it
else
if [[ "$verbose" -eq 1 ]]; then
debug_msg "replacing ${olddate}"
fi
_ed_overwrite_date "$filename" "$newdate"
fi
fi