diff --git a/scripts/treno b/scripts/treno new file mode 100755 index 0000000..bc5a325 --- /dev/null +++ b/scripts/treno @@ -0,0 +1,201 @@ +#!/bin/sh + +print_usage() { + cat <[^.]*)(?\\.\\d+)?(?:(?:(?[-+])(?\\d{2}):?(?\\d{2})?)|Z)$") | + (.no_tz + "Z" | fromdateiso8601) + + ("0"+.frac_sec | tonumber) + - (.tz_sgn + "60" | tonumber) + * ((.tz_hr // "0" | tonumber) * 60 + (.tz_min // "0" | tonumber)) + | todateiso8601 | strptime("%FT%TZ"); + + def time: + # Extracts "HH:MM" from a timestamp + parse_iso8601 | mktime | strftime("%R"); + + def delta($stop; $start): + # Computes the time elapsed between two dates + [$stop, $start] + | map(strptime($timefmt) | mktime) # seconds + | .[0] - .[1] + | ((./60) % 60) as $m + | (./3600 | floor) as $h + | (if $h > 0 then "\($h)h " else "" end) + "\($m)min"; + + def print_trip: + # Prints a trip "station(time) → station(time)" + (.duration // delta(.arrivalTime; .departureTime)) as $delta | + "\(.origin)(\(green(.departureTime | time)))" + + " → \(.destination)(\(.arrivalTime | time)) " + + blue($delta); + + def print_train: + # Prints the train name and its trip + "\(.train.description // .train.trainCategory): " + print_trip; + + def print_summary: + (.trains | length) as $ntrain | + (if $ntrain > 2 then (", " + red("\($ntrain-1) cambi")) + elif $ntrain == 2 then (", " + red("1 cambio")) + else "" end) as $switch | + "- " + print_trip + $switch + "\n " + + (.nodes | map(print_train) | join("\n ")); + + .solutions | map(.solution | print_summary) | join("\n\n")' +} + +handle_search() { + # Get station IDs + start_id=$(station_search "$1") + stop_id=$(station_search "$2") + shift 2 + + while :; do + case "$1" in + -d|--date) date=$2; shift ;; + -i|--interactive) interactive=1; shift ;; + -?*) print_usage ;; + *) break + esac + done + + results=$(route_search "$start_id" "$stop_id" "${date:-now}") + printf '%s\n\n' "$results" + + if test -n "$interactive"; then + # Ask user to select a train + info=$(printf '%s' "$results" | fzf --ansi --no-sort --disabled | cut -d: -f1) + # Print the train status + train_id=$(printf '%s' "$info" | cut -d: -f1 | rev | cut -d' ' -f 1 | rev) + # convert between different API conventions + station_id=$(printf '%s' "$start_id" | sed 's/^8300/S/g') + train_status "$train_id" --board "id:$station_id" + fi +} + +test $# -eq 0 && print_usage + +cmd="$1"; shift +case "$cmd" in + search) handle_search "$@" ;; + status) train_status "$@" ;; + *) print_usage +esac