#!/usr/bin/env python3
import time
import sys
import platform
import os
# import urllib.request
import urllib3
import requests
import http.client as http_client
import argparse
import json
import signal
import subprocess
from xml.etree import ElementTree as etree
from time import gmtime, strftime

def signal_handler(signal, frame):
        print('Exit...')
        sys.exit(0)

def sendmessage (message):
        mymessage=hostname.upper() + ': ' +message

        urllib3.disable_warnings()
        # http_client.HTTPConnection.debuglevel = 1

        url = ("%s/api/webhook/%s" % (baseurl, webhook))
        myreq = {}
        myreq['message'] = mymessage
        r = requests.post(url, json = { 'message': mymessage })
        if r.status_code == 200:
            print("Message has been sent successfully")
        else:
            print("Message sending FAILED")


__version__ = "1.0"
versionstring='TellMe v' + __version__

signal.signal(signal.SIGINT, signal_handler)

hostname=platform.node()
home=os.getenv("HOME")

parser = argparse.ArgumentParser(description='TellMe command line client')
parser.add_argument("-m", "--message", default="Your process finished", help="Message to send")
parser.add_argument('-v', '--version', action='version', version=versionstring)
parser.add_argument('-p', '--pid', action="store", dest="pid", type=int, default=0)
parser.add_argument('-n', '--interval', action="store", dest="interval", type=int, default=5, help="Set the interval of commands like watch that use it")
parser.add_argument('-w', '--watch', action="store", dest="watchcommand", help="Run the given command every n or 5 minutes")
parser.add_argument('-c', '--config', default=home +"/.config/tellme/config.json" ,help="Path to config file")
#print parser.parse_args()
args = parser.parse_args()

configfile = args.config
# Read config
if not os.path.isfile(configfile):
	print("No config file found in %s" %(configfile))
	exit(1)

config = None
with open(configfile) as cfgfile:
    config = json.load(cfgfile)

baseurl = config['url']
webhook = config['webhook']

message = args.message
if args.pid != 0:
	path = "/proc/%i" %(args.pid)
	print("Monitoring process %i" %(args.pid))
	while os.path.exists(path):
		time.sleep(10)
	sendmessage(message)
else:
    if(args.watchcommand):
        print("Watching %s every %i minutes" %(args.watchcommand,int(args.interval)))
        while True:
            output = subprocess.Popen(args.watchcommand, shell=True, stdout=subprocess.PIPE).stdout.read()
            print(output)
            sendmessage("|%s|" %(output))
            time.sleep(60*int(args.interval))
    else:
        sendmessage(message)