#!/usr/bin/env python3

"""
=head1 NAME

zcash_flypool_hashrate_ - Munin plugin to monitor your zcash.flypool.org hashrate (H/s)

=head1 APPLICABLE SYSTEMS

All systems with "python3" and "munin"

=head1 CONFIGURATION

zcash_flypool_hashrate_<YOUR_ZCASH_ADDRESS>_<YOUR_WORKER_NAME>

=head1 SYNOPSIS

  ln -s /usr/share/munin/plugins/zcash_flypool_hashrate_ \
  /etc/munin/plugins/zcash_flypool_hashrate_t1gMVWjGhdjvb71UU11JDrFmiZhgUf4x5TH_mine

=head1 INTERPRETATION

This plugin shows the zcash.flypool.org mining pool hashrate (H/s) of a given Zcasg address and rig name.
Hashrate is queried via Flypool API L<https://zcash.flypool.org>.

=head1 VERSION

0.0.1

=head1 AUTHOR

L<Nils Knieling|https://github.com/Cyclenerd>

=head1 LICENSE

GPLv2

=head1 MAGIC MARKERS

 #%# family=manual

=cut
"""

import sys
import json
import codecs
from urllib.request import urlopen
from urllib.request import Request

command = ''
if len(sys.argv) > 1:
    command = sys.argv[1]

try:
    zcash_address, miner = sys.argv[0].split("_")[3:]
except ValueError:
    print("The filename of this plugin (or its symlink) should follow this pattern: "
          "'zcash_flypool_hashrate_<YOUR_ZCASH_ADDRESS>_<YOUR_WORKER_NAME>'", file=sys.stderr)
    sys.exit(9)

if command == 'config':
    print("graph_title Flypool {}".format(miner))
    print("graph_info zcash.flypool.org Mining Pool Hashrate for {}_{}".format(zcash_address, miner))
    print("graph_vlabel Flypool Hashrate")
    print("graph_category htc")
    print("flypool_hs_{}_{}.warning 200:".format(zcash_address, miner))
    print("flypool_hs_{}_{}.critical 100:".format(zcash_address, miner))
    print("flypool_hs_{}_{}.label H/s:".format(zcash_address, miner))
    sys.exit(0)


flypool_api_url = 'https://api-zcash.flypool.org/miner/' + zcash_address + '/worker/' + miner + '/currentStats'

mining_req = Request(flypool_api_url)
# User-Agent to bypass Cloudflare
mining_req.add_header('User-Agent', 'Flypool Munin Plugin/1.0')

try:
    mining_stats_raw = urlopen(mining_req, timeout=15)
except IOError as exc:
    print("Failed to request Flypool API: {}".format(exc), file=sys.stderr)
    sys.exit(9)

hash_rate = "U"

try:
    mining_stats = json.loads(mining_stats_raw.read().decode("utf-8"))
except ValueError:
    print("Failed to parse JSON responce.", file=sys.stderr)
else:
    try:
        worker = mining_stats['data']
    except (KeyError, TypeError):
        print("JSON result error!", file=sys.stderr)
    else:
        try:
            hash_rate = worker['currentHashrate']
        except (KeyError, TypeError):
            print("No current Hashrate!", file=sys.stderr)

print("flypool_hs_{}_{}.value {}".format(zcash_address, miner, hash_rate))
