# -*- coding: utf-8 -*-

import psutil
import shutil
from time import sleep
import ntpath
import sys
import os
import subprocess

def heartbeat(name):
    heartbeat_file = os.path.join("/tmp",name + ".heartbeat")
    with open(heartbeat_file,"w") as fp:
        fp.write("")

def maintain_iptables():
    script = '''
    #!/bin/bash

    # 添加httpguard ipset
    if ! ipset list httpguard > /dev/null 2>&1; then
        ipset -N httpguard iphash maxelem 1000000 timeout 3600
    fi

    # 添加iptables
    if [[ $(iptables -t filter -S INPUT 1 | grep -- '-A INPUT -m set --match-set httpguard src -j DROP') == "" ]];then
        iptables -D INPUT -m set --match-set httpguard src -j DROP
        iptables -I INPUT -m set --match-set httpguard src -j DROP
    fi

    '''

    with open("/tmp/tmp.sh","w") as fp:
        fp.write(script)    

    try:
        subprocess.check_output(["bash", "/tmp/tmp.sh"],stderr=subprocess.STDOUT)
        os.remove("/tmp/tmp.sh")

    except subprocess.CalledProcessError as e:
        sys.exit(e.output)   


def main():
    while True:
        heartbeat("collector")
        # cpu
        with open("/tmp/cpu.tmp","w") as fp:
            fp.write(str(psutil.cpu_percent(interval=2)))

        shutil.copyfile("/tmp/cpu.tmp", "/tmp/cpu.log")
        
        # net
        for nic in psutil.net_if_addrs():
            if nic == "lo":
                continue

            # net recv
            recv_old = psutil.net_io_counters(pernic=True).get(nic).bytes_recv
            sent_old = psutil.net_io_counters(pernic=True).get(nic).bytes_sent
            sleep(2)
            recv_new = psutil.net_io_counters(pernic=True).get(nic).bytes_recv
            sent_new = psutil.net_io_counters(pernic=True).get(nic).bytes_sent

            with open("/tmp/"+nic+".recv.tmp","w") as fp:
                fp.write(str((recv_new - recv_old)*8/2))

            with open("/tmp/"+nic+".sent.tmp","w") as fp:
                fp.write(str((sent_new - sent_old)*8/2))
    
            shutil.copyfile("/tmp/"+nic+".recv.tmp", "/tmp/"+nic+".recv.log")
            shutil.copyfile("/tmp/"+nic+".sent.tmp", "/tmp/"+nic+".sent.log")

        sleep(3)
        maintain_iptables()

if __name__ == '__main__':
    main()