#!/usr/bin/env bash set -euo pipefail HABITS_FILE="${HABITS_FILE:-$HOME/.local/share/os/habits.md}" usage() { cat <<'EOF' Usage: habits Commands: open Open the habits file in $EDITOR new Add a new day to the habits file left Print today's habits that are not done yet EOF } ensure_file() { mkdir -p "$(dirname "$HABITS_FILE")" touch "$HABITS_FILE" } open_habits() { ensure_file "${EDITOR:-vi}" "$HABITS_FILE" } new_day() { ensure_file local date date="$(date +%F)" if grep -q "^# $date$" "$HABITS_FILE"; then echo "A habits entry for $date already exists: $HABITS_FILE" >&2 exit 1 fi local tmp tmp="$(mktemp)" { printf '# %s\n\n' "$date" printf '## Habits\n\n' while IFS= read -r habit; do [ -n "$habit" ] && printf -- '- [ ] %s\n' "$habit" done <<< "$HABITS" printf '\n## Metrics \n\n' while IFS= read -r metric; do [ -n "$metric" ] && printf -- '- %s\n' "$metric" ":" done <<< "$METRICS" printf '\n' cat "$HABITS_FILE" } > "$tmp" mv "$tmp" "$HABITS_FILE" echo "Added $date to $HABITS_FILE" } remaining_habits() { ensure_file local date date="$(date +%F)" awk -v date="$date" ' $0 == "# " date { in_day = 1; next } in_day && /^# / { exit } in_day && /^## Habits[[:space:]]*$/ { in_habits = 1; next } in_day && in_habits && /^## / { exit } in_day && in_habits && /^- \[ \] / { sub(/^- \[ \] /, "") print } ' "$HABITS_FILE" } case "${1:-}" in open) open_habits ;; new) new_day ;; left) remaining_habits ;; -h|--help|help) usage ;; *) usage >&2 exit 1 ;; esac