#!/bin/sh

# Do not manually set the next line, use `blister reset N`
start="20483"
blister=' ╭───┬───┬───┬───┬───╮
 │ 1 │ 3 │ 5 │ 7 │ 9 │
 ├───┼───┼───┼───┼───┤
 │ 0 │ 2 │ 4 │ 6 │ 8 │
 ╰───┴───┴───┴───┴───╯'

maxPills=10

reset(){
    current="$1"
    today=$(($(date -d 00:00 +%s) / (60 * 60 * 24)))
    start=$((today - maxPills + current))
    sed -i 's|^start=".*"$|start="'"$start"'"|' "$0"
}

isInt(){
    if echo "$1" | grep -q -e "^[0-9][0-9]*$" ; then
        return 0
    else
        return 1
    fi
}

help(){
    prog="$(basename "$0")"
    cat << EOF
'$prog' shows how many pills I should have on the blister($maxPills pills) by the end of the day.

USAGE: $prog [OPTIONS]

Options:
--help, -h Shows this help and exits.
'reset \$N' Reset the number of pills on the blister. '\$N' should be how many pill you will have by the end of the day. You will only need to reset if you skipped a day.
EOF
}

showpills(){
    today=$(($(date -d 00:00 +%s) / (60 * 60 * 24)))
    pills=$((maxPills - ((today - start) % maxPills)))
    echo "I should have $pills pills."
    remove=$(((maxPills - 1) - pills))
    if [ "$remove" -ge 0 ]; then
        echo "$blister" |
            sed 's|[0-'"$remove"']|◌|g;s|[0-9]|●|g'
    else
        echo "$blister" |
            sed 's|[0-9]|●|g'
    fi
}

if [ "0" != "$#" ]; then
    case "$1" in
        "reset")
            if ! isInt "$2"; then
                help 1>&2
                exit 1
            fi
            reset "$2"
            exit 0;
            ;;
        "--help"|"-h")
            help
            exit 0
            ;;
        *)
            help 1>&2
            exit 1
            ;;
    esac
fi

showpills
