#!/usr/bin/env python3

from datetime import datetime
from subprocess import check_output
from sys import argv, exit

INTERFACE = argv[1]
PUBKEY = argv[2]

NOW = datetime.timestamp(datetime.now())

try:
    result = check_output(['wg', 'show', INTERFACE, 'latest-handshakes']).decode('utf-8').splitlines()
except Exception as e:
    print('UNKNOWN: {}'.format(repr(e)))
    exit(3)

found_key = False
for line in result:
    pubkey, last_handshake = line.split()

    if pubkey == PUBKEY:
        overdue = NOW - int(last_handshake) - 120

        if overdue > 120:
            print('handshake is more than 120 seconds late!')
            exit(2)
        elif overdue > 15:
            print('handshake is more than 15 seconds late.')
            exit(1)
        else:
            print('received handshake a couple seconds ago')
            exit(0)

print('CRITICAL: {} not found in latest handshakes for {}'.format(PUBKEY, INTERFACE))
exit(2)