#!/bin/sh

TIME=0
# Work on the task (default: 25 min)
WORK_TIME=25
SHORT_BREAK_TIME=5
# Every 4 pomodori
LONG_BREAK_TIME=20

# Log informations
LOG_DIR="${HOME}/.pomodoro"
LOG_TASK_NAME=$(date +"week-%V-%Y.txt")
LOG_TASK_PATH="${LOG_DIR}/${LOG_TASK_NAME}"

# Task information (name, path, …)
TASK_NAME="${1}"
TASK_PATH="${LOG_DIR}/current.task"

initialize() {
  # Create the log dir
  if [ ! -d "${LOG_DIR}" ]; then
    mkdir -p -- "${LOG_DIR}"
  fi

  # Create the task file
  if [ ! -f "${TASK_PATH}" ]; then
    touch "${TASK_PATH}"
  fi

  # Create the task log file
  if [ ! -f "${LOG_TASK_PATH}" ]; then
    touch "${LOG_TASK_PATH}"
  fi
}

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

initialize

# Start working
startedTime=$(date +"%H:%M")

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

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

# Write logs
printf '%b' "$(date +"%A (%F) ${startedTime} → %H:%M") ${TASK_NAME}\n" >> "${LOG_TASK_PATH}"

# Toggle the sound
amixer -q set Master toggle

# Start break
if [ `expr ${num} % 4` -eq 0 ]; then
  BREAK_TIME=${LONG_BREAK_TIME}
  BREAK_MSG="Relax"
else
  BREAK_TIME=${SHORT_BREAK_TIME}
  BREAK_MSG="Pause"
fi

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
