#!/bin/sh

# Usage:
#
#   stateman <<insert state here>>
#
#     States:
#
#       Email
#       Offline
#       Role (Break3)
#       Hiring (Break2)
#       Lunch
#       Meeting
#       Project
#       Personal
#       System
#       Training
#       Available

cleanup() {
    rm -f $tmpfile
}

trap cleanup \
    EXIT INT QUIT TERM

input_var=$(echo $1 | tr '[:upper:]' '[:lower:]')

case "$input_var" in
          email)
            var=Email
            ;;
          offline)
            var=Offline
            ;;
          lunch)
            var=Lunch
            ;;
          meeting)
            var=Meeting
            ;;
          project)
            var=Project
            ;;
          personal)
            var=Personal
            ;;
          system)
            var=System
            ;;
          training)
            var=Training
            ;;
          available)
            var=Available
            ;;
          role)
            var=Break3
            ;;
          hiring)
            var=Break2
            ;;
          *)
            echo
            echo "                   Use a valid state, dummy."
            echo "     Email | Offline | Lunch | Meeting | Project | Personal"
            echo "         System | Training | Available | Role | Hiring"
            echo
            exit 1
            ;;
esac


cookie_filename=/tmp/stateman.cache
cookie_file=$(find $cookie_filename -mmin -720 2>/dev/null)

if [ "$cookie_file" != "$cookie_filename" ]
  then
    echo "Baking some warm, fresh cookies..."
    rm -f $cookie_filename
    curl -s  -c $cookie_filename --negotiate -u : --anyauth --location-trusted --max-redirs 10  'https://na.amzheimdall.com/sso/sentry?clientId=CSCentral-prod-na&redirect_uri=https://cscentral.amazon.com:443/gp/stores/www.amazon.com/gp/signin/gi-landat.html/146-6040352-1786033?landat=/gp/stores/www.amazon.com/gp/home/146-6040352-1786033' > /dev/null
    tmpfile=$(mktemp /tmp/cookies.sqlite.XXXXXXXXXX)
    ff_cookies="$(find $HOME/Library/Application\ Support/Vivaldi/Default/Cookies)"
    cat "$ff_cookies" >> $tmpfile
    sqlite3 -separator '    ' $tmpfile << EOF >> $cookie_filename
.mode tabs
.header off
select host_key,
case substr(host_key,1,1)='.' when 0 then 'FALSE' else 'TRUE' end,
path,
case secure when 0 then 'FALSE' else 'TRUE' end,
expires_utc,
name,
value
from cookies;
EOF
    # cleanup
fi

change=$(curl -s -L -w "%{http_code}\n" -X POST -u : \
  https://paragon-na.amazon.com/taw/switch-state \
  -b $cookie_filename \
  -H 'Content-Type: application/x-www-form-urlencoded' \
  -H 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.13; rv:58.0) Gecko/20100101 Firefox/58.0' \
  -d availabilityState=$var)

if [ "${change##*\}}" = 200 ]
then
  echo "GACD state set to $1! Woohoo!"
else
  echo "Something went wrong! It didn't work! :("
fi
