#!/usr/bin/env bash
# Trino 484: what's new, tested. The tutorial commands, in order (steps 0 and 1, then the cleanup).
set -euo pipefail

# Step 0 · Start the server
docker run -d --name t484-tuto --memory 2g trinodb/trino:484

until docker logs t484-tuto 2>&1 | grep -q "SERVER STARTED"; do sleep 2; done; echo "Trino is ready"

docker exec t484-tuto trino --execute "SELECT 1"

# Step 1 · Fetch the document and store it in Trino
curl -s "https://geo.api.gouv.fr/departements/69/communes?fields=nom,code,codesPostaux,population,codeEpci,centre&format=json" -o communes-69.json
wc -c < communes-69.json

{ printf "CREATE TABLE memory.default.communes_69 AS SELECT JSON '"; sed "s/'/''/g" communes-69.json; printf "' AS doc;\n"; } > load.sql
docker exec -i t484-tuto trino < load.sql

# Cleanup, at the end of the tutorial (after quit in the CLI):
# docker rm -f t484-tuto
# rm communes-69.json load.sql
