#!/bin/bash
set -e

# https://dev.netatmo.com/apidocumentation/weather#Available-data og velg værstasjon
# Filter på denne url i inspectoren for å få module ID og device ID
# https://app.netatmo.net/api/simplifiedfuturemeasure

# ELLER
# Gå til https://weathermap.netatmo.com/ og finn et punkt, hent URL fra "share"
# https://weathermap.netatmo.com//?zoom=16.1802283695561&type=temp&param=Filter&stationid=70%3Aee%3A50%3A2c%3A91%3A60&maplayer=Map&lang=undefined
# stationid=70%3Aee%3A50%3A2c%3A91%3A60 blir da device_id, renskrevet til 70:ee:50:2c:91:60 (replace %3A med :)

device_id="70:ee:50:2c:91:60"
module_id="02:00:00:2c:b2:30"

random_agent=$(shuf -n 1 <(curl -fsSL https://gist.githubusercontent.com/jakebathman/e57bad07fae95f4776f2588c919777d7/raw/cb998ab2c5e08501722544923c3f6b41e373d88b/user-agents.txt | grep -v '^$'))
access_token=$(curl --silent -A "$random_agent" https://weathermap.netatmo.com | grep 'accessToken' | sed -E 's/.*accessToken: "(.*)",/\1/')

# Time and 6 hours ago in Unix time
date_end=$(date +%s)
date_begin=$(($date_end - 3600))
# 6 hours in unix time is 21600
# 3 hours in unix time is 10800
# 1 hour in unix time is 3600


temp_humidity=$(curl --silent 'https://app.netatmo.net/api/getmeasure' --compressed -X POST \
-H "User-Agent: $random_agent" \
-H 'Accept: application/json, text/plain, */*' \
-H 'Accept-Language: nb,en-US;q=0.7,en;q=0.3' \
-H 'Accept-Encoding: gzip, deflate, br, zstd' \
-H "Authorization: Bearer $access_token" \
-H 'Content-Type: application/json;charset=utf-8' \
-H 'Origin: https://weathermap.netatmo.com' \
-H 'DNT: 1' \
-H 'Connection: keep-alive' \
-H 'Sec-Fetch-Dest: empty' \
-H 'Sec-Fetch-Mode: cors' \
-H 'Sec-Fetch-Site: cross-site' \
-H 'Sec-GPC: 1' \
-H 'Pragma: no-cache' \
-H 'Cache-Control: no-cache' \
--data-raw '{"date_begin":"'"$date_begin"'","date_end":"'"$date_end"'","scale":"max","device_id":"'"$device_id"'","module_id":"'"$module_id"'","type":"Temperature,Humidity"}' | jq '.body | last | .value[0][0]')

pressure=$(curl --silent 'https://app.netatmo.net/api/getmeasure' --compressed -X POST \
-H "User-Agent: $random_agent" \
-H 'Accept: application/json, text/plain, */*' \
-H 'Accept-Language: nb,en-US;q=0.7,en;q=0.3' \
-H 'Accept-Encoding: gzip, deflate, br, zstd' \
-H "Authorization: Bearer $access_token" \
-H 'Content-Type: application/json;charset=utf-8' \
-H 'Origin: https://weathermap.netatmo.com' \
-H 'DNT: 1' \
-H 'Connection: keep-alive' \
-H 'Sec-Fetch-Dest: empty' \
-H 'Sec-Fetch-Mode: cors' \
-H 'Sec-Fetch-Site: cross-site' \
-H 'Sec-GPC: 1' \
-H 'Pragma: no-cache' \
-H 'Cache-Control: no-cache' \
--data-raw '{"date_begin":"'"$date_begin"'","date_end":"'"$date_end"'","scale":"max","device_id":"70:ee:50:2c:91:60","module_id":"70:ee:50:2c:91:60","type":"Pressure"}' | jq '.body | last | .value[0][0]')

# echo "Tid:"
echo "Temperatur: $temp_humidity"
echo "Pressure: $pressure"
