clawdie-ai/scripts/date-format.sh

126 lines
2.7 KiB
Bash

#!/usr/bin/env bash
_date_format_repo_root() {
cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd
}
_date_format_env_file() {
printf '%s/.env\n' "$(_date_format_repo_root)"
}
_read_env_value() {
local key="$1"
local env_file
env_file="$(_date_format_env_file)"
if [ ! -f "$env_file" ]; then
return 1
fi
awk -F= -v key="$key" '
$1 == key {
value = substr($0, index($0, "=") + 1)
gsub(/^["'"'"']|["'"'"']$/, "", value)
print value
exit
}
' "$env_file"
}
_resolve_display_locale() {
if [ -n "${SYSTEM_LOCALE:-}" ]; then
printf '%s\n' "$SYSTEM_LOCALE"
return
fi
local env_locale
env_locale="$(_read_env_value SYSTEM_LOCALE 2>/dev/null || true)"
if [ -n "$env_locale" ]; then
printf '%s\n' "$env_locale"
return
fi
env_locale="${DISPLAY_LOCALE:-$(_read_env_value DISPLAY_LOCALE 2>/dev/null || true)}"
if [ -n "$env_locale" ]; then
printf '%s.UTF-8\n' "$(printf '%s' "$env_locale" | tr '-' '_')"
return
fi
if [ -n "${LANG:-}" ]; then
printf '%s\n' "$LANG"
return
fi
printf 'C.UTF-8\n'
}
_resolve_display_timezone() {
if [ -n "${TZ:-}" ]; then
printf '%s\n' "$TZ"
return
fi
local env_tz
env_tz="$(_read_env_value TZ 2>/dev/null || true)"
if [ -n "$env_tz" ]; then
printf '%s\n' "$env_tz"
return
fi
printf 'UTC\n'
}
_read_now_parts() {
local locale tz output
locale="$(_resolve_display_locale)"
tz="$(_resolve_display_timezone)"
if output=$(LC_TIME="$locale" TZ="$tz" date '+%d %b %Y %H %M %S' 2>/dev/null); then
printf '%s\n' "$output"
return
fi
TZ="$tz" date '+%d %b %Y %H %M %S'
}
format_display_date_now() {
local day month year hour minute second
read -r day month year hour minute second <<<"$(_read_now_parts)"
month="${month%.}"
printf '%s.%s.%s\n' "$day" "$month" "$year"
}
format_display_timestamp_now() {
local day month year hour minute second
read -r day month year hour minute second <<<"$(_read_now_parts)"
month="${month%.}"
printf '%s.%s.%s %s:%s:%s\n' \
"$day" "$month" "$year" "$hour" "$minute" "$second"
}
format_snapshot_stamp_now() {
local day month year hour minute second
read -r day month year hour minute second <<<"$(_read_now_parts)"
month="${month%.}"
printf '%s.%s.%s-%s%s\n' \
"$day" "$month" "$year" "$hour" "$minute"
}
if [[ "${BASH_SOURCE[0]}" == "$0" ]]; then
set -euo pipefail
case "${1:-}" in
display-date)
format_display_date_now
;;
display-ts)
format_display_timestamp_now
;;
snapshot-stamp)
format_snapshot_stamp_now
;;
*)
echo "Usage: $0 {display-date|display-ts|snapshot-stamp}" >&2
exit 1
;;
esac
fi