#!/bin/sh

# A small Pomodoro's timer for Taskwarrior.

## Vars
TIME=0
# Work on a task (default: 25 min)
WORK_TIME=25
# Take a small break
SHORT_BREAK_TIME=5

# Taskwarrior path
TASKWARRIOR_PATH="${HOME}/.task"
# Current task path
TASK_NAME="${1}"
TASK_PATH="${TASKWARRIOR_PATH}/.current.task"
TASK_ID=$(task description.is:"${TASK_NAME}" ids)

# --------- Dependancies ----------

# Verify Taskwarrior is installed
if ! command -v task > /dev/null; then
	printf '%b' "Please install Taskwarrior.\n"
	exit 1
fi

# Verify Taskwarrior is initialized
if [ ! -d "${TASKWARRIOR_PATH}" ]; then
	printf '%b' "Please initialize Taskwarrior.\n"
	exit 1
fi


# ------------- START -------------

# If the task doesn't already exists
if [ ! "${TASK_ID}" ]; then
	command task add "${TASK_NAME}"
	printf '%b' "Task '${TASK_NAME}' created.\n"
	TASK_ID=$(task description.is:"${TASK_NAME}" ids)
fi

## Working on the task
# Start the task
command task start "${TASK_ID}"
printf '%b' "${TASK_NAME} started.\n"

printf '%b' "${TASK_NAME}\n${TIME}" > "${TASK_PATH}"

# Tiny timer for ${WORK_TIME} minutes
while [ "${TIME}" != "${WORK_TIME}" ]; do
	sleep 60
	TIME=$((TIME+1))
	printf '%b' "${TASK_NAME}\n${TIME}" > "${TASK_PATH}"
done

# Stop the task
command task stop "${TASK_ID}"
printf '%b' "${TASK_NAME} stopped.\n"

## Break time
# Toggle the sound
amixer -q set Master toggle

BREAK_MSG="Pause"
BREAK_TIME="${SHORT_BREAK_TIME}"

printf '%b' "${BREAK_MSG}\n${BREAK_TIME}" > "${TASK_PATH}"

while [ "${BREAK_TIME}" -gt 0 ]; do
  sleep 60
  BREAK_TIME=$((BREAK_TIME-1))
  printf '%b' "${BREAK_MSG}\n${BREAK_TIME}" > "${TASK_PATH}"
done

# Toggle the sound
amixer -q set Master toggle

# Delete the task file
rm -f "${TASK_PATH}"

exit 0