#!/bin/bash
# This script is intended to be run via cron.

# It creates a folder structure in home for the current date in the following format:
# $HOME/ByDate/<Year>/<Month>/<Day>

# It also sets up a symlink in home: $HOME/Today
# This symlink will always point to the folder for the current date.

# Finally, it removes any folders without data, to prevent clutter.

# - Why did you make this?
# I remember things better when they have a date attached to them.
# You can use this for a primitive form of note-taking, but aside from notes -
# you can store any data this way.

LD_INTERNAL=1
. $(dirname $(realpath $0))/daisy.source

dir_name=ByDate
root_dir=$HOME/$dir_name
today_sym=$HOME/Today

# Present day
today=$(date -I)
year=$(echo $today | awk -F"-" '{print $1}')
month=$(echo $today | awk -F"-" '{print $2}')
day=$(echo $today | awk -F"-" '{print $3}')

set -e

function errorFn()
{
  error=$?
  if [[ $error -gt 0 ]];
  then
    echo "$LD_BIN error ($error): "
    perl -E 'say $!=shift' $error
  fi
  exit $error
}

# Error handling
trap errorFn ERR

# First we clear out empty folders, and remove the symlink if it exists
test -e "$root_dir" &&	find "$root_dir" -maxdepth 3 -type d -empty -print | xargs rm -rf
test -L "$today_sym" && rm -rf "$today_sym"

# Now we can set up today's directory
mkdir -p "$root_dir/$year/$month/$day"
cd $root_dir
ln -s "./$dir_name/$year/$month/$day" "$today_sym"
exitcode=@?
