#!/usr/bin/env python
import subprocess, re, os, sys, json
from subprocess import check_output
from urllib import request

# curl -s https://files.amp.hr/register.py | sudo GO2DIGITAL_TOKEN=secret python3

dmi_keywords = [
  'bios-vendor',
  'bios-version',
  'bios-release-date',
  'system-manufacturer',
  'system-product-name',
  'system-version',
  'system-serial-number',
  'system-uuid',
  'baseboard-manufacturer',
  'baseboard-product-name',
  'baseboard-version',
  'baseboard-serial-number',
  'baseboard-asset-tag',
  'chassis-manufacturer',
  'chassis-type',
  'chassis-version',
  'chassis-serial-number',
  'chassis-asset-tag',
  'processor-family',
  'processor-manufacturer',
  'processor-version',
  'processor-frequency',
]

def run(cmd):
    return check_output(cmd.split()).decode('utf-8').strip()

def hostnamectl():
    res = {}
    for line in map(str.strip, run('hostnamectl').split('\n')):
        [key, value] = list(map(str.strip, line.split(':')))
        key = key.lower().replace(' ', '_')
        res[key] = value
    return res


interfaces = ['eno1', 'enp2s0', 'enp3s0', 'eth0']

def main_ip():
    inet_re = re.compile(r'(?<=inet )(.*)(?=\/)', re.M)
    mac_re = re.compile(r'(?<=link/ether )([^ ]+)', re.M)

    for interface in interfaces:
        try:
            ip_output = run(f'ip addr show {interface}')
            inet = re.search(inet_re, ip_output)
            mac = re.search(mac_re, ip_output)
            if inet and mac:
                return {
                    'ip': inet.groups()[0],
                    'mac': mac.groups()[0],
                    'interface': interface,
                }
        except subprocess.CalledProcessError:
            pass


if __name__ == "__main__":
    info = {}
    info['hostname'] = run('hostname')
    info['ip_addresses'] = run('hostname --all-ip-addresses').split()
    info['dmi'] = {}
    for key in dmi_keywords:
        val = run(f'dmidecode -s {key}')
        if val == 'Default string' or val.lower().replace(' ', '-') == key:
            val = None
        info['dmi'][key.replace('-', '_')] = val

    info['hostnamectl'] = hostnamectl()
    info['main_ip'] = main_ip()

    if not info['main_ip']:
        print('Cannot determine main IP address')
        sys.exit(1)

    data = {
        'name': info['hostname'],
        'hostname': info['main_ip']['ip'],
        'info': info,
    }

    url = 'https://www.go2digital.hr/api/inventory/register/'
    #url = 'http://localhost:8000/api/inventory/register/'
    data = json.dumps(data).encode('utf8')
    req = request.Request(url, data=data, headers={
        'content-type': 'application/json',
        'authorization': f'Token {os.environ["GO2DIGITAL_TOKEN"]}',
    })

    with request.urlopen(req) as response:
        print(response.read())

