#!/bin/sh
# Show current train speed on ICE

main() {
  status=$(curl -X GET https://iceportal.de/api1/rs/status 2>/dev/null)
  tripInfo=$(curl -X GET https://iceportal.de/api1/rs/tripInfo/trip 2>/dev/null)

  if [[ -z $status || -z $tripInfo ]]; then
      return
  fi

  # Speed
  speed=$(echo $status | jq ".speed")

  # Next stop
  nextId=$(echo $tripInfo | jq ".trip.stopInfo.actualNext")
  nextStop=$(echo $tripInfo | jq ".trip.stops[] | select( .station.evaNr == $nextId )")

  nextStopName=$(echo $nextStop | jq -r ".station.name")
  nextStopArrival=$(echo $nextStop | jq ".timetable.actualArrivalTime")

  nextStopRemainingSeconds=$(expr $(expr $nextStopArrival / 1000) - $(date +%s))

  if [[ ${nextStopRemainingSeconds:0:1} == "-" ]]; then
    nextStopRemainingTime="Arribada!"
  else
    nextStopRemainingTime=$(date -d@$nextStopRemainingSeconds -u +%Hh%Mm%Ss)
  fi

  echo "  $nextStopName ·   $nextStopRemainingTime · 󰓅  $speed km/h"
}

main "$@"
