#!/bin/bash
#
# Get Vodafone Cube data in JSON format
#
# written and tested with 
# Vodafone Cube ZTE Model: MF289F - HW Version: T2 - SW Version: CR_VDFDEMF289FV1.0.0B08
#
# Get singe value e.g. with
# ./get_vodafone_cube_data.sh | jq -cr '.lte_rsrp'
#
# written 2026-02-22 by Christian Wulsch and ChatGPT
# version 2026-02-22ss

ROUTER="http://192.168.0.1"
PASS="Geheim"

COOKIE_JAR="/tmp/mf289f.cookies"

GET_PARAMS=(
  cell_id
  cr_version
  imei
  lte_rsrp
  network_type
  rscp
  rssi
  sim_imsi
  sinr
  wa_inner_version
  wan_lte_ca
  wifi_onoff_state
  Z_rssi
  Z_SINR
  mesh_switch
  mesh_role
  web_version
  wifi_chip1_ssid1_ssid
  wifi_start_mode
  wifi_mesh_deployed
  wifi_lbd_enable
  wifi_eacs_enable
)

#
# Functions
#

function ts() { 
  date +%s%3N; 
}

function implode() {
  delim="$1"
  elems="${*:2}"
  echo "${elems// /$delim}"
}

function login() {
  # 1) LD holen
  LD=$(curl --connect-timeout 10 -s -c "$COOKIE_JAR" \
    -H "X-Requested-With: XMLHttpRequest" \
    -H "Referer: $ROUTER/index.html" \
    "$ROUTER/goform/goform_get_cmd_process?isTest=false&cmd=LD&_=$(ts)" \
    | sed -n 's/.*"LD":"\([^"]*\)".*/\1/p')

  # 2) Hash berechnen (korrekt: inner & outer uppercase)
  H1=$(printf "%s" "$PASS" | openssl dgst -sha256 | awk '{print toupper($2)}')
  HASH=$(printf "%s%s" "$H1" "$LD" | openssl dgst -sha256 | awk '{print toupper($2)}')

  # 3) Login → setzt zwsd-Cookie
  curl --connect-timeout 10 -s -b "$COOKIE_JAR" -c "$COOKIE_JAR" \
    -H "X-Requested-With: XMLHttpRequest" \
    -H "Referer: $ROUTER/index.html" \
    -d "isTest=false&goformId=LOGIN&password=$HASH" \
    "$ROUTER/goform/goform_set_cmd_process"
}

function get_values() {
  values="$(implode '%2C' $*)"

  curl --connect-timeout 10 -s -b "$COOKIE_JAR" \
    -H "X-Requested-With: XMLHttpRequest" \
    -H "Referer: $ROUTER/index.html" \
    "$ROUTER/goform/goform_get_cmd_process?isTest=false&cmd=$values&multi_data=1&_=$(date +%s%3N)"

#    "$ROUTER/goform/goform_get_cmd_process?isTest=false&cmd=cr_version%2Cnetwork_type%2Crssi%2Crscp%2Clte_rsrp%2Ccell_id%2CZ_SINR%2Csinr%2CZ_rssi%2Cwan_lte_ca&multi_data=1&_=$(date +%s%3N)"
#    "$ROUTER/goform/goform_get_cmd_process?isTest=false&cmd=mesh_switch%2Cmesh_role%2Ccr_version%2Cweb_version%2Cwifi_chip1_ssid1_ssid%2Cwifi_start_mode%2Cwifi_mesh_deployed%2Cwifi_lbd_enable%2Cwifi_eacs_enable&multi_data=1&_==$(date +%s%3N)"
#    "$ROUTER/goform/goform_get_cmd_process?isTest=false&cmd=network_type%2Crssi%2Crscp%2Clte_rsrp%2Ccell_id%2CZ_SINR%2Csinr%2CZ_rssi%2Cwan_lte_ca%2Clte_ca_pcell_band%2Clte_ca_pcell_bandwidth%2Clte_ca_scell_band%2Clte_ca_scell_bandwidth%2Clte_ca_pcell_arfcn%2Clte_ca_scell_arfcn%2Clte_ca_scell_info&multi_data=1&_=$(ts)"
}

#
# Main
#

if get_values lte_rsrp | grep -q '"lte_rsrp":""'; then
  # echo "Re-Login nötig"
  login >/dev/null
fi

DATA="$(get_values ${GET_PARAMS[*]})"
echo "$DATA" | jq
