#!/usr/bin/env bash

#
# check args
#

if [[ $# -ne 3 ]]
then
   echo "usage: $0 year day"
   exit 1
fi

#
# check year and day
#

year=$(($2))

if [[ $year -gt 2015 ]]
then
    echo "invalid year: $2"
    echo "must be 2015 or later"
    exit 2
fi

day=$(($3))

if [[ $day -lt 1 ]] || [[ $day -gt 25 ]]
then
    echo "invalid day: $3"
    echo "must be between 1 and 25"
    exit 2
fi

#
# fetch input
#

input_directory="../data/$year/$day"
input_path="$input_directory/input.txt"

if ! [[ -f $input_path ]]
then
    mkdir -p $input_directory
    input_url="https://adventofcode.com/$year/day/$day/input"

    cookie_path="../cookie"
    if ! [[ -f $cookie_path ]]
    then
	echo "can't fetch input from $input_url without a \`cookie\` file at \`$cookie_path\`"
	echo "create this file with \`$ touch $cookie_path\`, then fill it with the \`session\` cookie from your browser"
	exit 3
    fi
       
    curl -s -b "$(cat ../cookie)" $input_url > $input_path
fi

language=$1
valid_languages=""
valid_language="false"

cd ..
for directory in $(ls .)
do
    if [[ -d $directory ]] && [[ -f $directory/bin/run ]]
    then
	valid_languages="$valid_languages, $directory"
	if [[ $language == $directory ]]; then
	    valid_language="true"
	fi
    fi
done

if ! $valid_language ; then
    echo "unsupported language $language"
    echo "supported languages are ${valid_languages:2}"
    exit 4
fi

#
# delegate language
#

cd $language
echo "Running problem $day from year $year in $language"
./bin/run $year $day