#!/usr/bin/env python2.7
import logging
import logging.handlers
import os
import subprocess
import time

LOG_FILE_PATH = '/var/log/synosupportdebug.log'

class CompressedFileHandler(logging.handlers.RotatingFileHandler):
    def doRollover(self):
        if self.stream:
            self.stream.close()
        if self.backupCount > 0:
            for i in xrange(self.backupCount - 1, 0, -1):
                src = '%s.%d.xz' % (self.baseFilename, i)
                dst = '%s.%d.xz' % (self.baseFilename, i + 1)
                if os.path.exists(src):
                    os.rename(src, dst)
            cmd = 'xz -fz %s -S .1.xz' % self.baseFilename
            try:
                subprocess.check_call(cmd.split(' '))
            except:
                raise RuntimeError('failed to compress log files.')
        if not self.delay:
            self.stream = self._open()

def create_logger(path):
    def decorate(func):
        formatter = logging.Formatter('%(asctime)s %(levelname)-8s: ' +
                                      '%(command)s\n%(message)s')
        handler = CompressedFileHandler(path, maxBytes=20000000, backupCount=30)
        handler.setFormatter(formatter)

        func.log = logging.getLogger(__name__)
        func.log.setLevel(logging.DEBUG)
        func.log.addHandler(handler)

        return func

    return decorate

def output_parser(msg):
    return '\t' + msg.replace('\n', '\n\t')

@create_logger(LOG_FILE_PATH)
def execute(command):
    try:
        p = subprocess.Popen(command.split(' '), stdout=subprocess.PIPE,
                                                 stderr=subprocess.PIPE)
        out, err = p.communicate()

        if p.returncode is not 0:
            err = err if len(err) else out
            execute.log.error(output_parser(err), extra={'command': command })
        else:
            execute.log.debug(output_parser(out), extra={'command': command })
    except Exception as e:
        execute.log.critical(output_parser(str(e)), extra={'command': command })

def execute_get_output(command):
    try:
        return subprocess.check_output(command.split(' '))
    except:
        return str('')

def default_gateway():
    out = execute_get_output('ip -4 route show default')
    arr = out.split(' ')
    return arr[2] if len(arr) == 6 else str('')

def is_qualcomm():
    out = execute_get_output('synogetkeyvalue /etc/synoinfo.conf unique')
    return False if out.startswith('synology_northstarplus_rt1900ac') else True

def show_qualcomm():
    # show interface's vlan entry
    execute('ssdk_sh vlan entry show')

    # show interface's link speed information
    for i in xrange(1, 6):
        execute('ssdk_sh port speed get {port_id}'.format(port_id=i))

def show_northstarplus():
    # show interface's link speed information
    execute('cat /proc/synobios/syno_switch_speed')

def show():
    # show interface configuration
    execute('ifconfig')
    execute('netstat -rn')

    # show qualcomm or northstarplus information
    show_qualcomm() if is_qualcomm() else show_northstarplus()

def test():
    # ping specific address.
    execute('ping -c 5 -W 3 8.8.4.4')
    execute('ping -c 5 -W 3 ' + default_gateway())

    # nslookup specific domain.
    execute('nslookup google.com')
    execute('nslookup synology.com')

def process():
    while True:
        show()
        test()
        time.sleep(60)

def main():
    process()

if __name__ == '__main__' :
    main()

