#!/usr/bin/env bash

OMERON_VERSION_DIR="${OMERON_VERSION_DIR:-$HOME/.local/share/omeron}"
OMERON_VERSION_FILE="$OMERON_VERSION_DIR/version"

version_read() {
  if [[ -f "$OMERON_VERSION_FILE" ]]; then
    source "$OMERON_VERSION_FILE"
    return 0
  fi
  return 1
}

version_write() {
  mkdir -p "$OMERON_VERSION_DIR"
  cat > "$OMERON_VERSION_FILE" <<VERSION
# Omeron Version File
OMERON_VERSION=1
OMERON_INSTALL_DATE="$(date '+%Y-%m-%d %H:%M:%S')"
OMERON_LAST_UPDATE="$(date '+%Y-%m-%d %H:%M:%S')"
VERSION
}

version_update() {
  mkdir -p "$OMERON_VERSION_DIR"
  if [[ -f "$OMERON_VERSION_FILE" ]]; then
    local tmp
    tmp="$(mktemp)"
    while IFS= read -r line; do
      case "$line" in
        OMERON_LAST_UPDATE=*) printf 'OMERON_LAST_UPDATE="%s"\n' "$(date '+%Y-%m-%d %H:%M:%S')" ;;
        *) printf '%s\n' "$line" ;;
      esac
    done < "$OMERON_VERSION_FILE" > "$tmp"
    mv "$tmp" "$OMERON_VERSION_FILE"
  else
    version_write
  fi
}
