from celery import shared_task from distutils.dir_util import copy_tree from .views import makewificonfig from .hostname import hostname import os import time import glob import tempfile import crypt import subprocess import datetime @shared_task def mkfirmware(device, path): BEFORE = os.getcwd() DEVICEDIR = "/opt/vpnmanager/device-config/%i/" % device.model.id SRCDIR = "/opt/vpnmanager/imagebuilder/%i/" % device.model.id if glob.glob(SRCDIR + "/.kumilock"): return False with open(SRCDIR + "/.kumilock", "w") as lock: lock.write("") tempdir = tempfile.TemporaryDirectory() copy_tree(DEVICEDIR, tempdir.name) # Write OpenVPN config with open(tempdir.name + "/etc/openvpn/client.conf", "w") as vpnconf: vpnconf.write(device.vpnconfig) # Write secret with open(tempdir.name + "/etc/vpnsecret", "w") as secret: secret.write('SECRET="%s"\nHOSTNAME="%s"' % (device.secret, hostname)) # Write password with open(tempdir.name + "/etc/shadow", "r") as shadow: password = crypt.crypt(device.password, crypt.mksalt(crypt.METHOD_MD5)) shadowin = shadow.read() with open(tempdir.name + "/etc/shadow", "w") as shadowout: shadowout.write(shadowin.replace("$PASSWORD", password)) # Write Wireless config with open(tempdir.name + "/etc/config/wireless", "r") as wireless: wirein = wireless.read() with open(tempdir.name + "/etc/config/wireless", "w") as wireout: wire = wirein.replace("$SSID", device.ssid or device.serial) wire = wire.replace("$KEY", device.key or "") wire = wire.replace("$ENC", "psk2" if device.key else "none") wireout.write(wire + "\n" + makewificonfig(device)) # Create compilation environment os.system("rm -rf " + SRCDIR + "/files/") os.mkdir(SRCDIR + "/files/") os.system("cp -r " + tempdir.name + "/* " + SRCDIR + "/files/") tempdir.cleanup() os.system("rm " + SRCDIR + "/bin/targets/ar71xx/generic/*") # Build image os.chdir(SRCDIR) try: subprocess.run(["/usr/bin/make"], shell=True) os.chdir(BEFORE) genfile = glob.glob( SRCDIR + "/bin/targets/ar71xx/generic/*squashfs-sysupgrade.bin" )[0] os.rename(genfile, "%s/%s.bin" % (path, device.id)) try: os.remove(SRCDIR + "/.kumilock") except FileNotFoundError: pass os.system("rm -rf " + SRCDIR + "/files/") os.system("rm " + SRCDIR + "/bin/targets/ar71xx/generic/*") return True except Exception as e: os.remove(SRCDIR + "/.kumilock") os.chdir(BEFORE) return False