#!/bin/bash set -euo pipefail year=2023 root=~/adventofcode${year} getinput() { curl -fsS -b "$root/cookie" -O "https://adventofcode.com/$year/day/$1/input" } getsamples() { curl -fsS "https://adventofcode.com/$year/day/$1" | awk '/
/ {sub("
", ""); CODE=1; IDX+=1} /<\/code>/ {CODE=0} CODE {print > sprintf("sample%d.in", IDX)}'
}

if [[ "$*" = "auto" ]]; then
    # get the current day in UTC with and without zero padding.
    # UTC is a few hours ahead of US Eastern time, so
    # it should match the day of the current puzzle even
    # if the clocks on tilde.town and AoC aren't synced exactly
    day_unpadded=$(TZ=UTC date '+%-d')
    day_padded=$(TZ=UTC date '+%0d')
    dir=$root/day$day_padded
elif (( $# == 1 || $# == 2 )); then
    day_unpadded=$(printf "%d" "$1")
    day_padded=$(printf "%02d" "$1")
    dir=${2:-}
else
    echo >&2 "usage: $0 day [out_dir]"
    echo >&2 "       $0 auto"
    exit 0
fi

if [[ -z "$dir" ]]; then
    dir=$root/day$day_padded
fi

if test -e "$dir"; then
    echo >&2 "'$dir' already exists! refusing to continue"
    exit 1
fi

cwd=${PWD:-`pwd`}
mkdir "$dir"
cd "$dir" || exit 1

error=0

if ! getinput "$day_unpadded"; then
    echo >&2 "error: failed to get input for day $day_unpadded"
    error=1
fi

if ! getsamples "$day_unpadded"; then
    echo >&2 "error: failed to get sample inputs for day $day_unpadded"
    error=1
fi

if [[ $error -ne 0 ]]; then
    # we might not have managed to grab any files
    # at all. try to clean up after ourselves by removing
    # the directory (if it's empty)
    if cd "$cwd" && rmdir --ignore-fail-on-non-empty "$dir" >&2; then
        if ! test -d "$dir"; then
            echo "cleaning up '$dir'"
        else
            echo "not cleaning up '$dir'"
        fi
    fi
fi

exit $error