#!/usr/bin/env python
#-*- coding: utf-8 -*-
#create:2015-10-08 by mao_kxu@massclouds.com

from django.core.urlresolvers import reverse
from django.http import HttpResponse,HttpResponseRedirect
from django.shortcuts import render_to_response,RequestContext
from django.contrib.auth.decorators import login_required
from mplatform.website.common.CommonPaginator import SelfPaginator
import time
from django.db import connection,transaction
from django.core.files import uploadedfile
from mplatform.utils.db import dbbase
import os
from  django.utils import log
import string
from mplatform.utils.file import file_operator
from mplatform.utils.commondef import get_all_hosts
import sys
reload(sys)
sys.setdefaultencoding('utf8')
logger = log.getLogger(__name__)

@login_required
def ListSSH(request):
     #获得部署网络
    db = dbbase.database()
    # create table webssh(
    #id integer primary key,
    #ip text,
    #username text,
    #password text,
    #update_time text
    #);
    list = db.select_fetchall("select id, ip, memo,update_time from debug_webssh")
    #print isolist
    #分页功能
    lst = SelfPaginator(request,list, 20)

    kwvars = {
        'lPage':lst,
        'request':request,
    }
    return render_to_response('DebugManage/ssh.list.html',kwvars,RequestContext(request))


#django.reqInMemoryUploadedFile
@login_required
def AddSSH(request):
    sshdict = {'ip':'','ip_errors':'','memo':'','memo_errors':''}
    errors_flag = 0
    cursor = connection.cursor()
    if request.method=='POST':
           #dir_name =
        sshdict['ip'] = request.POST["ip"]
        sshdict['memo'] = request.POST["memo"]
        update_time = time.strftime("%Y-%m-%d %H:%M:%S")
        cursor.execute("select COALESCE(max(id),0)+1 as new_id from debug_webssh")
        id = cursor.fetchone()[0]
        print id
        cursor.execute("INSERT INTO debug_webssh(id, ip, memo,update_time) values (%s, %s, %s, %s)", [id, sshdict['ip'], sshdict['memo'], update_time])
        transaction.commit()#commit_unless_managed()
        connection.commit()
        #2/配置文件持久化，并重启shellinabox服务
        config_file = '/etc/sysconfig/shellinaboxd'
        lines = open(config_file).readlines()
        new_text = []
        optstr = ''
        for sline  in lines :
            line = sline.replace('\n','')
            if '#' not in line and 'OPTS=' in line and ':SSH:' in line and '-t' in line and '-s' in line:
                optstr = line
                sshstr = '/%s:SSH:%s' % (sshdict['ip'],sshdict['ip'])
                if sshstr in line:
                    new_text.append(line + '\n')
                else:
                    new_text.append('%s -s %s\n' % (line,sshstr))
            else:
                new_text.append(line + '\n')
        if optstr == '':
            new_text.append('OPTS= -t -s /%s:SSH:%s\n' % (sshdict['ip'],sshdict['ip']))
                
        new_text2 = ''.join([line for line in new_text])
        with open(config_file, 'w') as f:
            f.write(new_text2)
        f.close()
        
        os.system("systemctl restart shellinaboxd")
        if errors_flag == 0 :
          return HttpResponseRedirect(reverse('listsshurl'))
    else:
        pass

    sql = "select ip from debug_webssh"
    cursor.execute(sql)
    existhosts = [h[0] for h in cursor.fetchall()]
    hosts = []
    for h in get_all_hosts():
        if h not in existhosts:
            hosts.append(h)

    kwvars = {
        'sshdict':sshdict,
        'request':request,
        'hosts':hosts
    }

    return render_to_response('DebugManage/ssh.add.html',kwvars,RequestContext(request))

@login_required
def DeleteSSH(request):
        db = dbbase.database()
        idlist = request.POST.getlist('id')
        str_id =  ""
        logger.debug('idlist=%s',idlist)
        for id in idlist:
            str_id=str_id+id+","
        str_id2 = str_id.rstrip(',')
        print 'str_id2 ='+str_id2
        #1/删除配置文件持久化，并重启shellinabox服务
        select_sql = "select ip from debug_webssh where id in (%s) " % str_id2
        websshlist = db.select_fetchall(select_sql)
        #print 'websshlist==========================='
        #print websshlist

        config_file = "/etc/sysconfig/shellinaboxd"
        lines = open(config_file).readlines()
        new_text = []
        for webssh in websshlist:
            for line  in lines :
                keyword = ' -s /'+webssh['ip']+':SSH:'+webssh['ip']
                if  keyword not in line:
                    new_text.append(line)
                else:
                    line = line.replace(keyword,'')
                    if ':SSH:' in line:
                        new_text.append(line)
        lines = new_text
        new_text = []
            
        new_text2 = ''.join([line for line in lines])
        with open(config_file, 'w') as f:
              f.write(new_text2)
        f.close()
        os.system("systemctl restart shellinaboxd")
        #2/删除数据库的相应信息
        delete_sql = "delete from debug_webssh where id in (%s)" % str_id2
        print 'delete_sql='+delete_sql
        db.execute(delete_sql)
        return HttpResponseRedirect(reverse('listsshurl'))


