#coding=utf-8

import os
import re
import sys
import socket
import hashlib
import urllib
import urllib2
import base64
import time
import commands

def md5(str):
    m = hashlib.md5()
    m.update(str)
    return  m.hexdigest()

def itoa(ascii_value):
    return chr(ascii_value)

def atoi(char):
    return ord(char)

def exit(text = None):
    if text:
        print text
    sys.exit()

def findall(regex, text):
    pattern = re.compile(regex)
    search_result = pattern.findall(text)
    return search_result

def create_standard_daemon():
    if os.fork() > 0:
        sys.exit(0)
    os.chdir('/')
    os.setsid()
    os.umask(0)
    if (os.fork() > 0):
        sys.exit(0)
    return True

def create_simple_daemon():
    if (os.fork() > 0):
        sys.exit(0)
    return True

def execmd(cmdString):
    status, output = commands.getstatusoutput(cmdString)
    return status, output

def http(url, params = None, mtimeout = 10, user = None, pwd = None):
    if user and pwd:
        #auth
        base64String = base64.encodestring("%s:%s" % (user, pwd))
        authheader =  "Basic %s" % base64String
        request = urllib2.Request(url)
        request.add_header("Authorization", authheader)
        response = urllib2.urlopen(request)
        return response.code, response.read()
    else:
        data = None
        if params:
            data = urllib.urlencode(params)
        request = urllib2.Request(url, data)
        response = urllib2.urlopen(url = request, timeout = mtimeout)
        return response.code, response.read()

def safe_reload(module_name):
    try:
        reload(module_name)
    except Exception as ex:
        pass

def write_file(file, content, is_append = False):
    way = 'w+'
    if is_append:
        way = 'a+'
    try:
        fd = open(file, way)
        fd.write(content)
        fd.close()
        return True
    except:
        return False

def get_file_content(file):
    fd = open(file, 'r')
    file_content = fd.read()
    fd.close()
    return file_content

def download(url, filename):
    """
    download file and save to spefic path 
    """
    try:
        urllib.urlretrieve(url, filename)
    except Exception as ex:     
        return False
    return True

def hostname():
	return socket.gethostname()

def local_ip():
	return socket.gethostbyname(socket.gethostname())

def local_ip_list():
	return socket.gethostbyname_ex(socket.gethostname())

def telnet(ip, port, timeout):
    socket.setdefaulttimeout(timeout)
    client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    client.connect((ip, port))
    client.close()
    return True

def proc_num_by_key_word(kwd):
    status, output = execmd("ps auxww | grep %s | grep -v grep | wc -l" % kwd)
    return int(output)

def del_file_before_days(dirname, days):
    if dirname[-1] != '/':
        dirname = dirname + '/'
    f_list = os.listdir(dirname)
    cur_time = time.time()
    for f in f_list:
        abs_path = dirname + f
        modify_time = os.path.getmtime(abs_path)
        time_diff = cur_time - modify_time
        days_diff =  ( time_diff / 3600 ) / 24
        if days_diff >= days:
            os.remove(abs_path)