#!/usr/bin/env bash
#
# Convert the list of episodes into JSON format - pass an argument to make it
# JSONP instead.
#
# Author: Dave Eddy <dave@daveeddy.com>
# Date: March 17, 2024
# License: MIT

varname=$1

baselink='https://ysap.sh'

# this is an "episode" object in the final json
read -d '' -r json <<-"EOF"
{
	"title": $title,
	"desc": $desc,
	"link": $link,
	"num": $num,
	"external": {
		"tiktok": $tiktok,
		"youtube": $youtube,
		"instagram": $instagram
	}
}
EOF

# read data
objects=()
while IFS=$'\t' read -r num title desc link tt yt ig; do
	object=$(jq -nc \
		--arg title "$title" \
		--arg desc "$desc" \
		--arg link "$baselink$link" \
		--argjson num "$num" \
		--arg tiktok "$tt" \
		--arg youtube "$yt" \
		--arg instagram "$ig" \
		"$json"
	) || exit
	objects+=("$object")
done < <(./make-list)

# generate output JSON
printf -v now '%(%s)T' -1
output=$(printf '%s\n' "${objects[@]}" | jq -n \
    --argjson date "$now" \
    --arg link "$baselink" \
    '{
        "name": "You Suck at Programming",
        "site": $link,
        "generated": $date,
        "episodes": [inputs]
     }'
)

# print the data (optionally as jsonp if the first arg is set)
if [[ -n $varname ]]; then
	output="const $varname = $output;"
fi
echo "$output"
