#!/bin/bash

today() {
  echo "Going to today"
  TODAYDIR="$AOCROOT/$CURRYEAR/day$CURRDAY" 
  if [ ! -d $TODAYDIR ]; then
    echo "> Doesn't exist, making"
    mkdir $TODAYDIR
  fi
  echo "> cd $TODAYDIR"
  cd $TODAYDIR
}

getproblem() {
  YR=$CURRYEAR
  DY=$CURRDAY

  PWD=$(pwd)
  PWD=${PWD#$AOCROOT/}
  echo $PWD
  if [[ "$PWD" =~ ^[1-9][0-9]{3}/day[0-2][0-9]$ ]]; then
    YR=${PWD:0:4}
    DY=${PWD:5:5}
    DY=${DY/day0/}
    DY=${DY/day/}
  else 
    echo "Changing to Today's Directory"
    cd $AOCROOT/$YR/day$DY
  fi

  if [[ -f "problem" ]]; then
    echo "Found problem file."
    if [[ $1 != "-f" ]]; then
      # Check if the file already exists
      echo "Not forcing overwrite."
      exit 1
    fi
  fi

  # Remove any zero padding from day
  DY=$(echo "$CURRDAY"|awk '$0*=1')
  echo "Getting problem at $CURRYEAR/day/$DY"
  elinks -dump https://adventofcode.com/$CURRYEAR/day/$DY > problem
  vim problem
}

getsessiontoken() {
  FULLCOOKIE=$(grep "adventofcode" $HOME/.elinks/cookies)
  if [[ ! -n "$FULLCOOKIE" ]]; then
    echo "Error pulling elinks cookie"
    exit 1
  fi
  echo $FULLCOOKIE | cut -d" " -f2
}

help() {
  echo "Usage: aoc [option]"
  echo "Available Options:"
  echo "" 
  echo "  getproblem      - Retrieve the problem for the day associated with the current directory"
  echo ""
  echo "  getsessiontoken - Echo the session token from the elinks cookie file"
  echo "" 
  echo "  help            - Display this message"
  echo "" 
}

case $1 in
  "getproblem") 
    getproblem $2
    ;;
  "getsessiontoken")
    getsessiontoken
    ;;
  *) 
    help
    ;;
esac