#!/usr/bin/env python

import ctypes
import ctypes.util
import argparse
import urllib2
import sys
from time import sleep, time


class SD(object):
    def __init__(self):
        self.sd = ctypes.CDLL(ctypes.util.find_library("systemd"))

    def ready(self):
        self.__notify("READY=1")

    def status(self, stat):
        self.__notify("STATUS=%s" % stat)

    def errno(self, errno):
        self.__notify("ERRNO=%d" % errno)

    def buserror(self, err):
        self.__notify("BUSERROR=%s" % err)

    def mainpid(self, pid):
        self.__notify("MAINPID=%d" % pid)

    def watchdog(self):
        self.__notify("WATCHDOG=1")

    def __notify(self, msg):
        #print msg
        self.sd.sd_notify(0, msg)


def main(args=sys.argv):
    parser = argparse.ArgumentParser()
    parser.add_argument("--url", help="Make sure this URL responds with a non-error HTTP code")
    parser.add_argument("--interval", default=30, type=int, help="Time between checks")
    parser.add_argument("--pid", default=None, type=int, help="Main process PID")
    parser.add_argument("--exit", default=False, action="store_true", help="Exit on error")
    args = parser.parse_args()

    sd = SD()

    while True:
        ok = True
        staus = ""
        try:
            if ok and args.url:
                t1 = time()
                ok = bool(urllib2.urlopen(args.url, timeout=10).read())
                t2 = time()
                status = "Responded in %.2fs" % (t2 - t1)
        except Exception as e:
            ok = False
            status = "Error: %s" % str(e)

        if args.pid:
            sd.mainpid(args.pid)
        if status:
            sd.status(status)

        if ok:
            sd.ready()
            sd.watchdog()
        else:
            if args.exit:
                break

        sleep(args.interval)


if __name__ == "__main__":
    sys.exit(main(sys.argv))
