#!/usr/bin/env python3
import requests


access_token = '{{ hetzner_authentication_ansible_vault }}'

node_exporter_txt_dir = '/var/lib/prometheus/node-exporter'
metrics_file = node_exporter_txt_dir + "/hetzner_metrics.prom"

query= {'per_page': '1000'}
headers = {'Authorization': 'Bearer ' + access_token}

try:
  response_volumes = requests.get("https://api.hetzner.cloud/v1/volumes", headers=headers, params=query)
  response_servers = requests.get("https://api.hetzner.cloud/v1/servers", headers=headers, params=query)
except requests.exceptions.RequestException as e:  # This is the correct syntax
  f = open(metrics_file, "w")
  f.write("\n")
  f.close()
  raise SystemExit(e)


if response_volumes.ok and response_servers.ok:
  
  
  volume_json = response_volumes.json()["volumes"]
  unattached_volume_count = 0
  for x in range(len(volume_json)):
    if volume_json[x]["server"] == None:
      unattached_volume_count+=1

  locked_servers_count = 0
  servers_json = response_servers.json()["servers"]
  for x in range(len(servers_json)):
    if servers_json[x]["locked"] == "true":
      locked_servers_count+=1

  ratelimit_limit = response_servers.headers['ratelimit-limit']
  ratelimit_remaining = response_servers.headers['ratelimit-remaining']
  
  
  f = open(metrics_file, "w")
  f.write(
  "hetzner_api_ratelimit_remaining " + str(ratelimit_remaining) + "\n" 
  + "hetzner_api_ratelimit_limit " + str(ratelimit_limit) + "\n" 
  + "hetzner_api_unattached_volumes " + str(unattached_volume_count) + "\n"
  + "hetzner_api_locked_servers " + str(locked_servers_count) + "\n"
  )
  f.close()
else:
  f = open(metrics_file, "w")
  f.write("\n")
  f.close()