aboutsummaryrefslogtreecommitdiffhomepage
path: root/bin/task/context
blob: 30e465f3e7384bea5e719c65b02cabc2f1d4d46b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
#! /bin/bash

# Usage:
#   context 1h2m30s (Update current context with given time)
#   context         (Check total time of each context)

LOG_FILE=~/log/.context && touch $LOG_FILE
context="$(cat ~/.task/context)"
time="$1"

# Get seconds from given string
_get_seconds() {
  # Modify input to fit the format that `date` can read
  hour=$(grep -o '[0-9.]\+h' <<<"$1" | tr -d h)
  min=$(grep -o '[0-9.]\+m'  <<<"$1" | tr -d m)
  sec=$(grep -o '[0-9.]\+s'  <<<"$1" | tr -d s)
  echo "${hour:-0}*3600 + ${min:-0}*60 + ${sec:-0}" | bc
}

# Update time of current context
if [ -n "$1" ]; then
  # If current conetxt is not given, exit with 1
  if [ -z "$context" ] || [ "$context" = none ]; then 
    exit 1
  fi

  given_seconds="$(_get_seconds "$time")"

  # Get total time of given time and current context time
  while read -r ctx sec; do
    if [ "$ctx" = "$context" ]; then
      total=$(( "$sec" + "$given_seconds" ))
      sed -i -E "s/^${context}.*/${context}\t${total}/" $LOG_FILE
      exit 0
    fi
  done <$LOG_FILE

  # Update Log file
  echo -e "$context\t${given_seconds}" >>$LOG_FILE
# Print times for each context
else
  while read -r ctx sec; do
    echo -ne "$ctx\t"
    date -u -d @"$sec" +%H:%M
  done <$LOG_FILE
fi