#!/bin/bash

set -e

while getopts 't:' opt
do
	case $opt in
		t)
			team=$OPTARG
			;;
		?)
			exit 1
			;;
	esac
done

gamePk=$(./livepk.sh -t $team)
if [[ -z $gamePk || "$gamePk" = 'null' ]]
then
	exit 1
fi

jqFilter='{gamePk} + (.gameData.teams | {awayTeam: .away.teamName, homeTeam: .home.teamName}) + (.liveData.plays.allPlays[] | (.result + (.about | {atBatIndex, halfInning, inning, isComplete, isScoringPlay, hasReview})))'
mlblive subscribe -g $gamePk | jq -Sc --unbuffered "$jqFilter" | sed -u 's/$/0/' | split -l 1 --filter="sqlite3 $DB '.mode ascii' '.separator ' '.import /dev/stdin playinfo'"
