import es, cfglib, playerlib, popuplib, services, time, datetime, gamethread, path, os, ftplib, usermsg, sqlite3, urllib2

#Plugin Information
info = es.AddonInfo() 
info.name     = 'iScrim'
info.version  = '3.1'
info.url      = 'http://www.intrepids.net/?q=iscrim'
info.basename = 'iscrim'
info.author   = 'QuAnTuM-woOdY'
__version__ = "3.1"
public_variable = "%s_version" % info.basename
es.ServerVar(public_variable, __version__, 'iScrim Version').makepublic()

#Config Information
config = cfglib.AddonCFG(es.getAddonPath("iscrim") + "/iscrim.cfg")
config.text("******************************")
config.text("       iScrim Settings")
config.text("******************************")
 
iscrim_mastername     = config.cvar("iscrim_mastername",     "Master Admin", "This is the Master Admin Name, this needs to be set so you can add other admins ingame")
iscrim_masterid       = config.cvar("iscrim_masterid",     "STEAM_x:x:xxx", "This is the Master Admin SteamID, this must be set")
iscrim_authtype       = config.cvar("iscrim_authtype",   1, "This is the method that's used to auth admin access to the menu, 1 for SQLite(Default), 2 for MySQL")
iscrim_demopress      = config.cvar("iscrim_demopress",   0, "If you would like demos automatically zipped and sent via ftp set this to 1")
config.text("")
config.text("******************************************************")
config.text(" Set the following only if authtype has been set to 2")
config.text("******************************************************")

iscrim_mysqlhost      = config.cvar("iscrim_mysqlhost",   "localhost", "MySQL Server Hostname/ip")
iscrim_mysqluser      = config.cvar("iscrim_mysqluser",      "", "MySQL Username")
iscrim_mysqlpass      = config.cvar("iscrim_mysqlpass",     "", "MySQL Password")
iscrim_mysqldb        = config.cvar("iscrim_mysqldb",  "", "MySQL Database")
config.text("")
config.text("*******************************************************")
config.text(" Set the following only if demopress has been set to 1")
config.text("*******************************************************")

iscrim_ftphost        = config.cvar("iscrim_ftphost",   "", "FTP Server Hostname/ip")
iscrim_ftpuser        = config.cvar("iscrim_ftpuser",      "", "FTP Username")
iscrim_ftppass        = config.cvar("iscrim_ftppass",     "", "FTP Password")
iscrim_ftppath        = config.cvar("iscrim_ftppath",     "/", "FTP Path, if you do not want the demos in the root of your FTP then change this accordingly")
config.write()

#Set Paths
gamedir = path.path(str(es.ServerVar('eventscripts_gamedir')))
mapdir = gamedir.joinpath('maps/')
dbpath = es.getAddonPath('iscrim') + '/'

#Global Intialization
allowspectators = es.ServerVar('mp_allowspectators')
allowspectators.set(0)
es.set("scrim_mode", 0)
es.makepublic("scrim_mode")
currentmap = es.ServerVar('eventscripts_currentmap')

#Database Open
def dbopen():
    global connection, cursor
    if iscrim_authtype == 1:
        connection = sqlite3.connect(dbpath + 'iScrim.db')
        cursor = connection.cursor()
    if iscrim_authtype == 2:
        exec("import MySQLdb")
        connection = MySQLdb.connect (host = str(iscrim_mysqlhost), user = str(iscrim_mysqluser), passwd = str(iscrim_mysqlpass), db = str(iscrim_mysqldb))
        cursor = connection.cursor()

#Database Close
def dbclose():
    if iscrim_authtype == 1:
        connection.commit()
    cursor.close()
    connection.close()

#Query Functions
def fetchall(): 
    trueValues = [] 
    result = cursor.fetchall() 
    if not result: 
        return None 
    for value in result: 
        if len(value) > 1: 
            trueValues.append(value) 
        else: 
            trueValues.append(value[0]) 
    return trueValues

def fetchone(): 
    one = cursor.fetchone() 
    if not one: 
        return None 
    if len(one) == 1: 
        return one[0] 
    return one

#Load Function
def load():

    #Run the Config
    config.execute()

    #Build Database
    dbopen()
    cursor.execute("CREATE TABLE IF NOT EXISTS admins(SteamId varchar(255) unique, Name TEXT)")
    if iscrim_authtype == 1:
        cursor.execute("INSERT OR REPLACE INTO admins(SteamId, Name) VALUES ('%s', '%s')" % (iscrim_masterid, iscrim_mastername))
    if iscrim_authtype == 2:
        cursor.execute("REPLACE INTO admins(SteamId, Name) VALUES ('%s', '%s')" % (iscrim_masterid, iscrim_mastername))
    dbclose()

    #Registers
    es.regclientcmd('menusup', 'iscrim/menusup', 'Activates the Admin Menu')
    es.regclientcmd('lookup', 'iscrim/lookup', 'Activates the SteamID Look Up Menu')
    es.addons.registerClientCommandFilter(teamlock)
    es.addons.registerSayFilter(chatfilter)

    #Set Globals
    global MenuMain, MenuAdminAdd, MenuAdminRemove, MenuKickBanT, MenuKickBanCT, MenuMove, MenuMap, MenuKick, MenuBan, MenuChat, MenuKickBan, MenuAdmin, MenuDemo, MenuLookUp, MenuLookUpType, MenuUpdate

    #Clear Settings
    setBoot(1)
    setUpdate(0)
    setCTscore(0)
    setTscore(0)
    setMute(0)

    #Build the Menus
    MenuMain = None
    MenuAdminAdd = None
    MenuAdminRemove = None
    MenuKickBanT = None
    MenuKickBanCT = None
    MenuMove = None
    MenuMap = None
    MenuKick = None
    MenuBan = None
    MenuChat = None
    MenuKickBan = None
    MenuAdmin = None
    MenuDemo = None
    MenuLookUp = None
    MenuLookUpType = None
    MenuUpdate = None
    MenuMain = popuplib.easymenu('MenuMain',None, menu_main)
    MenuAdminAdd = popuplib.easymenu('MenuAdminAdd',None, menu_adminadd)
    MenuAdminRemove = popuplib.easymenu('MenuAdminRemove',None, menu_adminremove)
    MenuKickBanT = popuplib.easymenu('MenuKickBanT',None, menu_kickbant)
    MenuKickBanCT = popuplib.easymenu('MenuKickBanCT',None, menu_kickbanct)
    MenuMove = popuplib.easymenu('MenuMove',None, menu_move)
    MenuMap = popuplib.easymenu('MenuMap',None, menu_map)
    MenuKick = popuplib.easymenu('MenuKick',None, menu_kick)
    MenuBan = popuplib.easymenu('MenuBan',None, menu_ban)
    MenuChat = popuplib.easymenu('MenuChat',None, menu_chat)
    MenuKickBan = popuplib.easymenu('MenuKickBan',None, menu_kickban)
    MenuAdmin = popuplib.easymenu('MenuAdmin',None, menu_admin)
    if iscrim_demopress == 1:
        MenuDemo = popuplib.easymenu('MenuDemo',None, menu_demo)
    MenuUpdate = popuplib.easymenu('MenuUpdate',None, menu_update)
    MenuLookUp = popuplib.easymenu('MenuLookUp',None, menu_lookup)
    MenuLookUpType = popuplib.easymenu('MenuLookUpType',None, menu_lookuptype)
    MenuLookUp.settitle("iScrim - SteamID Look Up via Legit-Proof")
    MenuLookUpType.settitle("iScrim - SteamID Look Up Type")
    MenuLookUpType.addoption('leagues', "Leagues")
    MenuLookUpType.addoption('ban', "Ban Lists")
    MenuMain.settitle("iScrim")
    MenuMain.addoption('lo3', "Execute lo3")
    MenuMain.addoption('pregame', "Execute Pregame")
    MenuMain.addoption('map', "Change Map")
    MenuMain.addoption('move', "Change Player Team")
    MenuMain.addoption('chat', "Chat Control")
    MenuMain.addoption('kickban', "Kick/Ban Control")
    MenuMain.addoption('admin', "Add/Remove Admin")
    if iscrim_demopress == 1:
        MenuMain.addoption('demo', "Move Demos")
    MenuAdmin.submenu(MenuMain)
    MenuAdmin.addoption('addadmin', "Add Admin") 
    MenuAdmin.addoption('removeadmin', "Remove Admin")
    MenuChat.submenu(MenuMain)
    MenuChat.addoption('mutet', "Mute Terrorist")
    MenuChat.addoption('mutect', "Mute Counter Terrorist")
    MenuChat.addoption('muteall', "Mute Counter Terrorist & Terrorist")
    MenuChat.addoption('unmute', "Unmute Counter Terrorist & Terrorist")
    MenuKickBan.submenu(MenuMain)
    MenuKickBan.addoption('bant', "Kickban: Terrorist")
    MenuKickBan.addoption('banct', "Kickban: Counter Terrorist")
    MenuKickBan.addoption('kick', "Kick: Player")
    MenuKickBan.addoption('ban', "Kickban: Player")
    MenuKickBanT.settitle("iScrim - Are you sure?")
    MenuKickBanCT.settitle("iScrim - Are you sure?")
    MenuChat.settitle("iScrim - Select Chat Action:")
    MenuAdmin.settitle("iScrim - Add/Remove Admin:")
    if iscrim_demopress == 1:
        MenuDemo.submenu(MenuMain)
        MenuDemo.settitle("iScrim - Are you sure?")
        MenuDemo.addoption('yes', "Yes")
    MenuUpdate.submenu(MenuMain)
    MenuUpdate.settitle("iScrim - Update - Updating will restart the map, Are you sure?")
    MenuUpdate.addoption('yes', "Yes")
    MenuKickBanT.submenu(MenuKickBan)
    MenuKickBanT.addoption('yes', "Yes")
    MenuKickBanCT.submenu(MenuKickBan)
    MenuKickBanCT.addoption('yes', "Yes")
    gamethread.delayed(10, es.server.queuecmd, ('changelevel de_dust'))

#Console Commands
def menusup():
    userid = es.getcmduserid()
    if admin(userid) == True:
        MenuMain.send(userid)

def lookup():
    userid = es.getcmduserid()
    MenuLookUp.delete()
    global MenuLookUp
    MenuLookUp = popuplib.easymenu('MenuLookUp',None, menu_lookup)
    MenuLookUp.settitle("iScrim - SteamID Look Up via Legit-Proof")
    myPlayerList = playerlib.getPlayerList('#human')
    for ply in myPlayerList:
        MenuLookUp.addoption(ply.steamid, ply.name)
    MenuLookUp.send(userid)

#Admin Auth Function
def admin(userid):
    steamid = es.getplayersteamid(userid)
    cursor.execute("SELECT SteamId FROM admins WHERE SteamId='%s'" % steamid)
    result = cursor.fetchone() 
    steamidcheck = result[0]
    if es.getplayersteamid(userid) == steamidcheck:
        return True

#Team Lock Function
def teamlock(userid, args): 
    if es.ServerVar('scrim_mode') == "1":
        if es.getplayercount(args[1]) >= 5:
            return args[0].lower() != "jointeam"
        else:
            return True
    else:
        return True

#Chat Lock Function
def chatfilter(userid, text, teamonly):
    if teamonly or mute == 0:
        return (userid, text, teamonly)
    if mute == 1:
        return (0, None, None)
    if es.getplayerteam(userid) == mute:
        return (0, None, None)

#Change Team Function
def changeteam(userid, teamid): 
    es.server.queuecmd('es_xchangeteam %s %s' % (userid, teamid))

#Menu Functions
lookupuserid = {}

def menu_lookup(userid, choice, popupname):
    if choice.startswith('STEAM_'):
        lookupuserid[userid] = choice
    MenuLookUpType.settitle("iScrim - SteamID Look Up Type - %s" % choice)
    MenuLookUpType.send(userid)

def menu_lookuptype(userid, choice, popupname):
    if choice == 'leagues':
        usermsg.motd(userid, 2, 'iScrim - Leagues Look Up: %s' % lookupuserid[userid], 'http://www.legit-proof.com/search.php?method=guid&query=%s' % lookupuserid[userid])
        del lookupuserid[userid]
    if choice == 'ban':
        usermsg.motd(userid, 2, 'iScrim - Ban Lists Look Up: %s' % lookupuserid[userid], 'http://www.legit-proof.com/search.php?method=bans&query=%s' % lookupuserid[userid])
        del lookupuserid[userid]

def menu_main(userid, choice, popupname):
    if choice == 'lo3':
        filename = gamedir + '/cfg/lo3.cfg'
        inputFile = file(filename, 'r')
        data = inputFile.read()
        inputFile.close()
        this = 'say "'
        that = 'say '
        data = data.replace(this, that)
        outputFile = file(filename, 'w')
        outputFile.write(data)
        outputFile.close()
        es.server.queuecmd('exec lo3.cfg')

    if choice == 'pregame':
        es.server.queuecmd('exec pregame.cfg')
    if choice == 'map':
        MenuMap.delete()
        global MenuMap
        MenuMap = popuplib.easymenu('MenuMap',None, menu_map)
        MenuMap.submenu(MenuMain)
        MenuMap.settitle("iScrim - Select Map Change:")
        for cs_map in sorted(mapdir.files('*de*.bsp'), cmp=lambda x,y: cmp(x.basename(), y.basename())): 
            MenuMap.addoption(cs_map.namebase , cs_map.namebase )
        MenuMap.send(userid)
    if choice == 'chat':
        MenuChat.send(userid)
    if choice == 'kickban':
        MenuKickBan.send(userid)
    if choice == 'move':
        MenuMove.delete()
        global MenuMove
        MenuMove = popuplib.easymenu('MenuMove',None, menu_move)
        MenuMove.submenu(MenuMain)
        MenuMove.settitle("iScrim - Select Player to move:")
        myPlayerList = playerlib.getPlayerList('#human')
        for ply in myPlayerList:
            MenuMove.addoption(ply.steamid, ply.name)
        MenuMove.send(userid)
    if choice == 'admin':
        MenuAdmin.send(userid)
    if choice == 'demo':
        MenuDemo.send(userid)
    if choice == 'update':
        MenuUpdate.send(userid)

def menu_chat(userid, choice, popupname):
    if choice == 'unmute':
        setMute(0)
    if choice == 'muteall':
        setMute(1)
    if choice == 'mutet':
        setMute(2)
    if choice == 'mutect':
        setMute(3)

def menu_kickban(userid, choice, popupname):
    if choice == 'bant':
        MenuKickBanT.send(userid)
    if choice == 'banct':
        MenuKickBanCT.send(userid)
    if choice == 'kick':
        MenuKick.delete()
        global MenuKick
        MenuKick = popuplib.easymenu('MenuKick',None, menu_kick)
        MenuKick.submenu(MenuKickBan)
        MenuKick.settitle("iScrim - Select Player to kick:")
        myPlayerList = playerlib.getPlayerList('#human')
        for ply in myPlayerList:
            MenuKick.addoption(ply.steamid, ply.name)
        MenuKick.send(userid)
    if choice == 'ban':
        MenuBan.delete()
        global MenuBan
        MenuBan = popuplib.easymenu('MenuBan',None, menu_ban)
        MenuBan.submenu(MenuKickBan)
        MenuBan.settitle("iScrim - Select Player to kick/ban:")
        myPlayerList = playerlib.getPlayerList('#human')
        for ply in myPlayerList:
            MenuBan.addoption(ply.steamid, ply.name)
        MenuBan.send(userid)

def menu_admin(userid, choice, popupname):
    if choice == 'addadmin':
        MenuAdminAdd.delete()
        global MenuAdminAdd
        MenuAdminAdd = popuplib.easymenu('MenuAdminAdd',None, menu_adminadd)
        MenuAdminAdd.submenu(MenuAdmin)
        MenuAdminAdd.settitle("iScrim - Select Player to add:")
        myPlayerList = playerlib.getPlayerList('#human')
        for ply in myPlayerList:
            MenuAdminAdd.addoption(ply.steamid, ply.name)
        MenuAdminAdd.send(userid)
    if choice == 'removeadmin':
        MenuAdminRemove.delete()
        global MenuAdminRemove
        MenuAdminRemove = popuplib.easymenu('MenuAdminRemove',None, menu_adminremove)
        MenuAdminRemove.submenu(MenuAdmin)
        MenuAdminRemove.settitle("iScrim - Select Player to remove:")
        myPlayerList = playerlib.getPlayerList('#human')
        cursor.execute("SELECT SteamId, Name FROM admins")
        rows = cursor.fetchall()
        for row in rows:
            MenuAdminRemove.addoption(row[0], row[1])
        MenuAdminRemove.send(userid)

def menu_demo(userid, choice, popupname):
    if choice == 'yes':
        es.msg('#multi',"#lightgreen:: Move demos selected, stopping current SourceTV demo ::")
        es.msg('#multi',"#lightgreen:: The server will now pause to do work.... ::")
        es.server.queuecmd('tv_stoprecord')
        gamethread.delayed(2, demopress, ())
        gamethread.delayed(10, es.msg, ('#multi', '#lightgreen:: Demos zipped and moved ::'))

def menu_update(userid, choice, popupname):
    if choice == 'yes':
        es.msg('#multi',"#lightgreen:: iScrim Update selected, stopping current SourceTV demo ::")
        es.msg('#multi',"#lightgreen:: The server will now pause to do work, then restart map ::")
        es.server.queuecmd('tv_stoprecord')
        gamethread.delayed(2, iupdate, ())
        gamethread.delayed(3, es.msg, ('#multi', '#lightgreen:: Downloading and Updating... ::'))
        gamethread.delayed(5, es.msg, ('#multi', '#lightgreen:: Disabling iScrim... ::'))
        gamethread.delayed(5, es.server.queuecmd, ('es_unload iscrim'))
        gamethread.delayed(7, es.msg, ('#multi', '#lightgreen:: Enabling iScrim... ::'))
        gamethread.delayed(7, es.server.queuecmd, ('es_load iscrim'))
        gamethread.delayed(9, es.msg, ('#multi', '#lightgreen:: Restarting Map... ::'))
        gamethread.delayed(11, es.server.queuecmd, ('changelevel %s' % es.ServerVar('eventscripts_currentmap')))
        gamethread.delayed(16, es.msg, ('#multi', '#lightgreen:: iScrim Updated ::'))

def menu_adminadd(userid, choice, popupname):
    if choice.startswith('STEAM_'):
        playername = es.getplayername(es.getuserid(choice))
        if iscrim_authtype == 1:
            cursor.execute("INSERT OR REPLACE INTO admins (Name, SteamId) VALUES ('%s', '%s')" % (playername, choice))
            connection.commit()
        if iscrim_authtype == 2:
            cursor.execute("REPLACE INTO admins (Name, SteamId) VALUES ('%s', '%s')" % (playername, choice))
        es.tell(userid, "You just added %s(%s) as an admin" % (playername, choice))
        
def menu_adminremove(userid, choice, popupname):
    if choice.startswith('STEAM_'):
        cursor.execute("SELECT Name FROM admins WHERE SteamId='%s'" % choice)
        result = cursor.fetchone() 
        delsteam = result[0]
        cursor.execute("DELETE FROM admins WHERE SteamId='%s'" % choice)
        if iscrim_authtype == 1:
            connection.commit()
        es.tell(userid, "You just deleted %s(%s) as an admin" % (delsteam, choice))

def menu_kickbant(userid, choice, popupname):
    if choice == 'yes':
        kickteam(2)

def menu_kickbanct(userid, choice, popupname):
    if choice == 'yes':
        kickteam(3)
        
def menu_move(userid, choice, popupname):
    if choice.startswith('STEAM_'):
        if es.getplayerteam(es.getuserid(choice)) == 2:
            changeteam(es.getuserid(choice), 3)
        if es.getplayerteam(es.getuserid(choice)) == 3:
            changeteam(es.getuserid(choice), 2)
            
def menu_map(userid, choice, popupname):
    es.server.queuecmd('changelevel %s' % choice)
                
def menu_kick(userid, choice, popupname):
    if choice.startswith('STEAM_'):
        es.server.queuecmd("kickid %s" % es.getuserid(choice))

def menu_ban(userid, choice, popupname):
    if choice.startswith('STEAM_'):
        es.server.queuecmd("kickid %s" % es.getuserid(choice))
        es.server.queuecmd("banid 1440 %s" % (choice))
        es.server.queuecmd("writeid")
        es.server.queuecmd("writeip")

#Download and Update iScrim Function
def iupdate():
    u = urllib2.urlopen('http://intrepids.net/files/iscrim.rar') 
    filename = es.getAddonPath('iscrim') + '/iscrim.py'
    localfile = open(filename, 'w') 
    localfile.write(u.read()) 
    localfile.close()

#Demo Zip and Upload Function
def demopress():
    os.chdir (gamedir)
    if str(os.name).lower() == 'posix':
        ftype = 'tgz'
    else:
        ftype = 'zip'
    for cs_demos in sorted(gamedir.files('*.dem'), cmp=lambda x,y: cmp(x.basename(), y.basename())):
        if str(os.name).lower() == 'posix':
            if os.path.getsize(cs_demos) <= 400000:
                os.system ("rm -f %s" % cs_demos)
            else:
                os.system ("tar -czvf %s.tgz %s" % (cs_demos.namebase, cs_demos.name))
        if str(os.name).lower() == 'nt':
            if os.path.getsize(cs_demos) <= 400000:
                os.system ("del %s" % cs_demos)
            else:
                os.system ("zip.cfg -1 %s.zip %s" % (cs_demos.namebase, cs_demos.name))
    session = ftplib.FTP('%s' % str(iscrim_ftphost),'%s' % str(iscrim_ftpuser),'%s' % str(iscrim_ftppass))
    for cs_files in sorted(gamedir.files("*.%s" % ftype), cmp=lambda x,y: cmp(x.basename(), y.basename())):
        myfile = open(cs_files,'rb')
        session.cwd("%s" % str(iscrim_ftppath))
        session.storbinary("STOR %s" % cs_files.name, myfile)
        if str(os.name).lower() == 'posix':
            os.system ("rm -f %s.dem" % cs_files.namebase)
        if str(os.name).lower() == 'nt':
            os.system ("del %s.dem" % cs_files.namebase)
        myfile.close()
        if str(os.name).lower() == 'posix':
            os.system ("rm -f %s.tgz" % cs_files.namebase)
        if str(os.name).lower() == 'nt':
            os.system ("del %s.zip" % cs_files.namebase)
    session.quit()

#Kick Team Function
def kickteam(value):
    if value == 2:
        team = '#t'
        es.msg('#multi',"#lightgreen :: Kick Banned :: #default Terrorist #lightgreen ::")
    if value == 3:
        team = '#ct'
        es.msg('#multi',"#lightgreen :: Kick Banned :: #default Counter Terrorist #lightgreen ::")
    myPlayerList = playerlib.getPlayerList(team)
    for ply in myPlayerList:
        es.server.queuecmd("kickid %s" % ply.userid)
        es.server.queuecmd("banid 1440 %s" % (ply.steamid))
        es.server.queuecmd("writeid")
        es.server.queuecmd("writeip")

#Map Start Function
def es_map_start(ev):
    if update == 0:
        u = urllib2.urlopen('http://intrepids.net/files/update.txt')
        line = u.readline()
        if line > info.version:
            setUpdate(1)
            MenuMain.addoption('update', "Update iScrim (Update Found)")
    setMute(0)
    es.server.queuecmd('tv_stoprecord')
    currentmap.set(ev['mapname'])
    if boot == 0:
        if iscrim_demopress == 1:
            demopress()
    if boot == 1:
        setBoot(0)

#Round Functions
def round_start(ev):
    global showcash
    showcash = 1
    if es.ServerVar('scrim_mode') == "1":
        if es.getplayercount() <= 2:
            es.server.queuecmd('tv_stoprecord')
        else:
            es.server.queuecmd('tv_record auto-%s-%s' % (time.strftime('%Y%m%d-%H%M'), es.ServerVar('eventscripts_currentmap')))
        allowspectators.set(0)
        tttotal = get_score('#t') + tscore
        ctttotal = get_score('#ct') + ctscore
        if tttotal + ctttotal >= 16:
            es.msg('#multi',"#lightgreen :: #defaultScore #lightgreen:: #defaultCT: #lightgreen%s #defaultT: #lightgreen%s ::"% (ctttotal, tttotal))
    if es.ServerVar('scrim_mode') == "0":
        es.server.queuecmd('tv_stoprecord')
        allowspectators.set(1)
        setCTscore(0)
        setTscore(0)

def round_end(ev):
    if es.ServerVar('scrim_mode') == "1":
        tttotal = get_score('#t') + tscore
        ctttotal = get_score('#ct') + ctscore
        if tttotal == 15 and ctttotal == 15:
            es.server.queuecmd('scrim_mode 0')
            es.server.queuecmd('mp_restartgame 1')
            gamethread.delayed(5, es.msg, ('#multi', "#lightgreen :: #defaultTie #lightgreen::"))
            gamethread.delayed(5, es.msg, ('#multi', "#lightgreen :: #defaultTie #lightgreen::"))
            gamethread.delayed(5, es.msg, ('#multi', "#lightgreen :: #defaultTie #lightgreen::"))
            gamethread.delayed(5, es.msg, ('#multi', "#lightgreen :: #defaultTie #lightgreen::"))
        elif tttotal == 16:
            es.server.queuecmd('scrim_mode 0')
            es.server.queuecmd('mp_restartgame 1')
            gamethread.delayed(5, es.msg, ('#multi', "#lightgreen :: #defaultTerrorist Win #lightgreen::"))
            gamethread.delayed(5, es.msg, ('#multi', "#lightgreen :: #defaultTerrorist Win #lightgreen::"))
            gamethread.delayed(5, es.msg, ('#multi', "#lightgreen :: #defaultTerrorist Win #lightgreen::"))
            gamethread.delayed(5, es.msg, ('#multi', "#lightgreen :: #defaultTerrorist Win #lightgreen::"))
        elif ctttotal == 16:
            es.server.queuecmd('scrim_mode 0')
            es.server.queuecmd('mp_restartgame 1')
            gamethread.delayed(5, es.msg, ('#multi', "#lightgreen :: #defaultCounter Terrorist Win #lightgreen::"))
            gamethread.delayed(5, es.msg, ('#multi', "#lightgreen :: #defaultCounter Terrorist Win #lightgreen::"))
            gamethread.delayed(5, es.msg, ('#multi', "#lightgreen :: #defaultCounter Terrorist Win #lightgreen::"))
            gamethread.delayed(5, es.msg, ('#multi', "#lightgreen :: #defaultCounter Terrorist Win #lightgreen::"))
        elif get_score('#ct') + get_score('#t') == 15:
            setCTscore(get_score('#t'))
            setTscore(get_score('#ct'))
            set_score('#ct', 0)
            set_score('#t', 0)
            myPlayerList = playerlib.getPlayerList('#ct')
            for ply in myPlayerList:
                changeteam(ply.userid, 2)
            myPlayerList = playerlib.getPlayerList('#t')
            for ply in myPlayerList:
                changeteam(ply.userid, 3)
            gamethread.delayed(10, es.msg, ('#multi', "#lightgreen :: #defaultTEAMS SWAPPED #lightgreen::"))
            gamethread.delayed(11, es.msg, ('#multi', "#lightgreen :: #defaultLIVE IN 30 SECONDS #lightgreen:: #defaultScore #lightgreen:: #defaultCT: #lightgreen%s #defaultT: #lightgreen%s ::"% (ctscore, tscore)))
            gamethread.delayed(12, es.msg, ('#multi', "#lightgreen :: #defaultLIVE IN 30 SECONDS #lightgreen:: #defaultScore #lightgreen:: #defaultCT: #lightgreen%s #defaultT: #lightgreen%s ::"% (ctscore, tscore)))
            gamethread.delayed(13, es.msg, ('#multi', "#lightgreen :: #defaultLIVE IN 30 SECONDS #lightgreen:: #defaultScore #lightgreen:: #defaultCT: #lightgreen%s #defaultT: #lightgreen%s ::"% (ctscore, tscore)))
            gamethread.delayed(10, es.centermsg, ('LIVE IN 30 SECONDS'))
            gamethread.delayed(11, es.centermsg, ('LIVE IN 29 SECONDS'))
            gamethread.delayed(12, es.centermsg, ('LIVE IN 28 SECONDS'))
            gamethread.delayed(13, es.centermsg, ('LIVE IN 27 SECONDS'))
            gamethread.delayed(14, es.centermsg, ('LIVE IN 26 SECONDS'))
            gamethread.delayed(15, es.centermsg, ('LIVE IN 25 SECONDS'))
            gamethread.delayed(16, es.centermsg, ('LIVE IN 24 SECONDS'))
            gamethread.delayed(17, es.centermsg, ('LIVE IN 23 SECONDS'))
            gamethread.delayed(18, es.centermsg, ('LIVE IN 22 SECONDS'))
            gamethread.delayed(19, es.centermsg, ('LIVE IN 21 SECONDS'))
            gamethread.delayed(20, es.centermsg, ('LIVE IN 20 SECONDS'))
            gamethread.delayed(21, es.centermsg, ('LIVE IN 19 SECONDS'))
            gamethread.delayed(22, es.centermsg, ('LIVE IN 18 SECONDS'))
            gamethread.delayed(23, es.centermsg, ('LIVE IN 17 SECONDS'))
            gamethread.delayed(24, es.centermsg, ('LIVE IN 16 SECONDS'))
            gamethread.delayed(25, es.centermsg, ('LIVE IN 15 SECONDS'))
            gamethread.delayed(26, es.centermsg, ('LIVE IN 14 SECONDS'))
            gamethread.delayed(27, es.centermsg, ('LIVE IN 13 SECONDS'))
            gamethread.delayed(28, es.centermsg, ('LIVE IN 12 SECONDS'))
            gamethread.delayed(29, es.centermsg, ('LIVE IN 11 SECONDS'))
            gamethread.delayed(30, es.centermsg, ('LIVE IN 10 SECONDS'))
            gamethread.delayed(31, es.centermsg, ('LIVE IN 9 SECONDS'))
            gamethread.delayed(32, es.centermsg, ('LIVE IN 8 SECONDS'))
            gamethread.delayed(33, es.centermsg, ('LIVE IN 7 SECONDS'))
            gamethread.delayed(34, es.centermsg, ('LIVE IN 6 SECONDS'))
            gamethread.delayed(35, es.centermsg, ('LIVE IN 5 SECONDS'))
            gamethread.delayed(36, es.centermsg, ('LIVE IN 4 SECONDS'))
            gamethread.delayed(37, es.centermsg, ('LIVE IN 3 SECONDS'))
            gamethread.delayed(38, es.centermsg, ('LIVE IN 2 SECONDS'))
            gamethread.delayed(39, es.centermsg, ('LIVE IN 1 SECOND'))
            gamethread.delayed(40, es.msg, ('#multi', "#lightgreen :: RESTART 1 ::"))
            es.server.queuecmd('es_delayed 40 mp_restartgame 1')
            gamethread.delayed(42, es.msg, ('#multi', "#lightgreen :: RESTART 2 ::"))
            es.server.queuecmd('es_delayed 41 mp_restartgame 1')
            gamethread.delayed(47, es.msg, ('#multi', "#lightgreen :: RESTART 3 ::"))
            es.server.queuecmd('es_delayed 42 mp_restartgame 5')
            gamethread.delayed(50, es.msg, ('#multi', "#lightgreen :: LIVE :: #defaultScore #lightgreen:: #defaultCT: #lightgreen%s #defaultT: #lightgreen%s ::"% (ctscore, tscore)))
            if mute == 2:
                setMute(3)
            elif mute == 3:
                setMute(2)

#Set/Get Value Functions
def setCTscore(value):
    global ctscore
    ctscore = value

def setBoot(value):
    global boot
    boot = value

def setUpdate(value):
    global update
    update = value

def setTscore(value):
    global tscore
    tscore = value

def setMute(value):
    global mute
    mute = value
    if value == 0:
        es.msg('#multi',"#lightgreen :: Counter Terrorist & Terrorist :: #default unmuted #lightgreen ::")
    if value == 1:
        es.msg('#multi',"#lightgreen :: Counter Terrorist & Terrorist :: #default muted #lightgreen ::")
    if value == 2:
        es.msg('#multi',"#lightgreen :: Terrorist :: #default muted #lightgreen ::")
    if value == 3:
        es.msg('#multi',"#lightgreen :: Counter Terrorist :: #default muted #lightgreen ::")

def get_score(team):
    teamscores = {}
    for index in es.createentitylist('cs_team_manager'):
        teamscores[es.getindexprop(index, 'CTeam.m_iTeamNum')] = es.getindexprop(index, 'CTeam.m_iScore')
    if team == '#t':
        return int(teamscores[2])
    if team == '#ct':
        return int(teamscores[3])

def set_score(team, amount):
    es.server.cmd('es score set %s %s' % (team, amount))

#Player Based Functions
def player_activate(ev):
    if es.ServerVar('tv_enable') == 1 and es.getplayercount() == 2:
        dbopen()
    elif es.ServerVar('tv_enable') == 0 and es.getplayercount() == 1:
        dbopen()
    userid = int(ev['userid'])
    gamethread.delayed(5, es.menu, (25, userid, "Welcome to a Clean Scrim Server!\nPowered by iScrim via EventScripts.\n \nUse the console command lookup to view player proof on Legit-Proof.\n \nYou can get iScrim @ www.intrepids.net."))

reset_list = []

def player_changename(ev):
    if es.getplayerteam(ev['userid']) == mute:
        if ev['es_steamid'] in reset_list:
            reset_list.remove(ev['es_steamid'])
            gamethread.delayed(0.1, es.msg, ('#multi', "#lightgreen "))
            gamethread.delayed(0.1, es.msg, ('#multi', "#lightgreen "))
            gamethread.delayed(0.1, es.msg, ('#multi', "#lightgreen "))
            gamethread.delayed(0.1, es.msg, ('#multi', "#lightgreen "))
            gamethread.delayed(0.1, es.msg, ('#multi', "#lightgreen "))
            gamethread.delayed(0.1, es.msg, ('#multi', "#lightgreen "))
            gamethread.delayed(0.1, es.msg, ('#multi', "#lightgreen "))
        else:
            gamethread.delayed(0.1, es.msg, ('#multi', "#lightgreen "))
            gamethread.delayed(0.1, es.msg, ('#multi', "#lightgreen "))
            gamethread.delayed(0.1, es.msg, ('#multi', "#lightgreen "))
            gamethread.delayed(0.1, es.msg, ('#multi', "#lightgreen "))
            gamethread.delayed(0.1, es.msg, ('#multi', "#lightgreen "))
            gamethread.delayed(0.1, es.msg, ('#multi', "#lightgreen "))
            gamethread.delayed(0.1, es.msg, ('#multi', "#lightgreen "))
            reset_list.append(ev['es_steamid'])

disco = {}

def player_disconnect(ev):
    if es.ServerVar('tv_enable') == es.getplayercount():
        dbclose()
    if es.getplayercount() <= 3:
        es.server.queuecmd('tv_stoprecord')
    if es.ServerVar('scrim_mode') == "1":
        if ev['reason'] == "Disconnect by user.":
            disco[ev['networkid']] = time.time()

def player_spawn(ev):
    if es.ServerVar('scrim_mode') == "1":
        discotime = time.time() - disco[ev['es_steamid']]
        if discotime <= 60:
            playerlib.getPlayer(ev["userid"]).set("cash", 0)
            del disco[ev['es_steamid']]

def round_freeze_end(ev):
    global showcash
    showcash = 0

def unload():
    dbclose()
    es.addons.unregisterClientCommandFilter(teamlock)
    es.addons.unregisterSayFilter(chatfilter)
    es.unregclientcmd('menusup')
    es.unregclientcmd('lookup')
    MenuMain.delete()
    MenuAdminAdd.delete()
    MenuAdminRemove.delete()
    MenuKickBanT.delete()
    MenuKickBanCT.delete()
    MenuMove.delete()
    MenuMap.delete()
    MenuKick.delete()
    MenuBan.delete()
    MenuChat.delete()
    MenuKickBan.delete()
    MenuAdmin.delete()
    MenuDemo.delete()