wg-ops/generate.py

55 lines
1.6 KiB
Python
Raw Normal View History

import os
import sys
2022-01-27 11:12:58 +08:00
import getopt
2022-03-12 04:11:50 +08:00
from libwgopparser import Parser, errprint
2022-02-02 02:52:53 +08:00
if __name__ == "__main__":
2022-03-19 05:22:50 +08:00
opts, args = getopt.getopt(sys.argv[1:], 'hiko:', ["tmux", "systemd"])
2022-02-02 03:51:21 +08:00
opts = {p[0]: p[1] for p in opts}
if '-h' in opts:
print('''wg-ops: WireGuard configuration extended generator
OPTIONS
-h Display this help and quit.
-k Output generated config to standard output
-o <filename> Output generated config to file. Default is {source_filename}.gen
2022-03-19 05:22:50 +08:00
--tmux Use tmux mode
--systemd Use systemd mode
2022-02-07 08:24:17 +08:00
HELP
For latest help please view https://github.com/Kiritow/wg-ops
''')
exit(0)
2022-02-02 02:52:53 +08:00
filepath = args[0]
filename = os.path.basename(filepath)
2022-02-02 03:51:21 +08:00
with open(filepath, 'r') as f:
2022-02-15 15:56:57 +08:00
content = f.read()
2022-02-02 02:52:53 +08:00
2022-03-12 04:11:50 +08:00
wgop_basepath = os.path.dirname(os.path.realpath(sys.argv[0]))
parser = Parser(wgop_basepath)
2022-02-15 15:56:57 +08:00
if '-i' in opts:
2022-03-16 19:47:52 +08:00
parser.opt_allow_modify = True
2022-02-15 15:56:57 +08:00
parser.opt_source_path = filepath
2022-03-17 18:02:29 +08:00
if '--tmux' in opts:
parser.opt_use_tmux = True
2022-03-19 05:22:50 +08:00
if '--systemd' in opts:
parser.opt_use_systemd = True
2022-02-15 15:56:57 +08:00
2022-02-02 02:52:53 +08:00
parser.parse(content)
parser.compile_interface()
parser.compile_peers()
2022-03-19 04:46:52 +08:00
parser.compile_final()
2022-02-02 02:52:53 +08:00
if '-k' in opts or ('-o' in opts and opts['-o'] == '-'):
print(parser.get_result())
elif '-o' in opts:
2022-02-15 16:47:25 +08:00
errprint('Saving to {}...'.format(opts['-o']))
with open(opts['-o'], 'w') as f:
2022-02-02 02:52:53 +08:00
f.write(parser.get_result())
else:
2022-02-15 16:47:25 +08:00
errprint('Saving to {}.gen...'.format(filename))
with open('{}.gen'.format(filename), 'w') as f:
f.write(parser.get_result())