vq3srv/vq3srv

84 lines
2.6 KiB
Python
Executable file

#!/usr/bin/env python3
from argparse import ArgumentParser
from os import system
from random import shuffle
from sys import exit
from yaml import safe_load
def parse_arguments():
desc = 'host a q3 server'
parser = ArgumentParser(description=desc)
parser.add_argument('-m', '--gamemode', default='ffa')
parser.add_argument('-f', '--fraglimit', type=int)
parser.add_argument('-t', '--timelimit', type=int)
parser.add_argument('-b', '--bots', type=int, default=0)
parser.add_argument('-c', '--config', default='config.yml')
parser.add_argument('-B', '--bootstrap')
return parser.parse_args()
def gen_confline(param, value, archive=False):
set_cmd = 'seta' if archive else 'set'
return '{} {} "{}"\n'.format(set_cmd, param, value)
def gen_maplist(maplist):
shuffle(maplist)
num = 1
stmpl = 'set d{} "map {} ; set nextmap vstr d{}"\n'
script = str()
while maplist:
nextnum = 1 if len(maplist) == 1 else num + 1
script += stmpl.format(num, maplist.pop(), nextnum)
num += 1
script += 'vstr d1\n'
return script
def gen_addbots(count, level='3', names=list()):
shuffle(names)
btmpl = 'addbot {} {}\n'
script = str()
for bot in names[:count]:
script += btmpl.format(bot, level)
return script
def main():
args = parse_arguments()
cfg_data, bvars, svars = str(), dict(), dict()
try:
with open(args.config, 'r') as config_file:
cfg = safe_load(config_file)
if args.bootstrap:
with open(args.bootstrap, 'r') as bootstrap_file:
bvars.update(safe_load(bootstrap_file))
assert args.gamemode in cfg['gamemodes']
except FileNotFoundError as error:
exit('Config `{}` not found!'.format(error.filename))
except AssertionError:
exit('Wrong game mode `{}` specified!'.format(args.gamemode))
smaps = cfg['gamemodes'][args.gamemode]['maps']
svars.update(cfg['gamemodes'][args.gamemode]['vars'])
if args.fraglimit:
svars.update({'fraglimit': args.fraglimit})
if args.timelimit:
svars.update({'timelimit': args.timelimit})
for param in bvars:
cfg_data += gen_confline(param, bvars[param], archive=True)
for param in svars:
cfg_data += gen_confline(param, svars[param])
cfg_data += gen_maplist(smaps)
if args.bots:
cfg_data += gen_addbots(args.bots, **cfg['bots'])
with open(cfg['autoexec'], 'w+') as config:
config.write(cfg_data)
system('sudo -u {} {}'.format(cfg['user'], cfg['cmd']))
if __name__ == '__main__':
main()