#!/usr/bin/env zsh

source ~/bin/zendesk_env.sh

get_url="https://${zd_hostname}/api/v2/users/${zd_user_id}/tickets/assigned"
earliest=$(curl --silent --verbose --location --header "Authorization:  Basic ${basic_auth_token}" --header "Accept:  application/json" --header "Content-Type:  application/json" ${get_url} | \
    jq -r '.tickets[] | pick(.id, .created_at, .status) | select(.status != "closed") | select(.status != "solved") | .created_at' | sort -u | head -1)
se=$(date -d "${earliest} -1 day" +%s)

print "Earliest open created date is:  $(date -d "${earliest}") (${se})" >&2

for log in ~/timetracker/staging/*.log; do
    local tstamp=$(sed '/^$/d' ${log} | tail -1 | awk -F: '{print $1":"$2":"$3}')
    local st=$(date -d "${tstamp}" +%s)
    touch -d ${tstamp} ${log}
    if [[ "${st}" -le "${se}" ]]; then
        print "Deleting ${log}..." >&2
        rm ${log}
    else
        print "Preserving ${log}..." >&2
    fi
done

