#!/bin/bash # TODO: If $stop similar to "Bus Station" then reject and suggest user tries supplying a route number to see when their next bus leaves the station # TODO: Fix duplication of destinations and routes in result read stop # function to provide data to a for loop _jq() { echo ${json} | base64 --decode | jq -r ${1} } _liveresult() { livetimes=$(curl --fail --silent https://admin.libertybus.je/api/v1/soj/stop_updates/${stop}) jq '.[]|=sort_by(.service_number)' > sorted.json exitcode=$? livetimeslen=$(echo ${livetimes} | jq '. | length') if [ $exitcode != 0 ]; then echo "cURL error - exiting." exit 1 elif [ $livetimeslen = 0 ]; then echo "No results found." exit 1 else outtypes=(destination service_number eta) for type in ${outtypes[@]}; do case $type in destination) result="$result Dest:" ;; service_number) result="$result | Routes:" ;; eta) result="$result | ETAs: " ;; *) ;; esac for json in $(echo "${livetimes}" | jq -r '.[] | @base64'); do result="$result $(_jq '.'$type''), " done result=$(echo $result | sed 's/,$//') done echo -e $result exit 0 fi } _stopsreturn() { stops=$(curl --fail --silent https://admin.libertybus.je/api/v1/stops/"${stop}") exitcode=$? stopslen=$(echo ${stops} | jq '. | length') # if length of $stops array is 1 then only one bus stop matches and we can return live times for that stop if [ $exitcode != 0 ]; then echo "cURL error - exiting." exit 1 elif [ $stopslen = 1 ]; then stop=$(echo ${stops} | jq '.[].stop_id') _liveresult elif [ $stopslen = 0 ]; then echo "No results found." exit 1 # multiple stops returned in $stops so we will return stop names and codes so user can retry else for json in $(echo "${stops}" | jq -r '.[] | @base64'); do result="$result Stop: $(_jq '.name') -" result="$result Code: $(_jq '.stop_id') |" done result=$(echo $result | sed 's/ |$//') echo -e $result exit 0 fi } if [ "$stop" == "-h" ] || [ "$stop" == "--help" ]; then echo "Usage: '!bus ' where is either the 4 digit stop code, the full unique or partial bus stop name. If a bus stop name is used and there are multiple matches then a list of matching stops will be returned with their codes." exit 0 elif [[ "$stop" =~ ^-?[0-9]+$ ]] && [ $(echo ${#stop} == 4) ]; then _liveresult elif [[ -z "${stop// }" ]]; then echo "Input empty. Usage: '!bus ' where is either the 4 digit stop code, the full unique or partial bus stop name. If a bus stop name is used and there are multiple matches then a list of matching stops will be returned with their codes." exit 1 else _stopsreturn fi