#!/usr/bin/python3

import glob
import os
from pathlib import Path
import shutil
import subprocess
import sys
import tarfile
import tempfile
import time
import xml.etree.ElementTree as ET
import argparse
from datetime import datetime

os.system(f"logger -t EurogardBackup 'Starting backup process'")
#os.system(f"logger -t EurogardBackup '{sys.argv}'")

UPLOAD_FOLDER = "/tmp/upload"
EUROGARD_DATA_FOLDER = "/app/eurogard"
EUROGARD_CERTS_FOLDER = "/app/eurogard/certs"
TMP_EUROGARD_CERTS_FOLDER = "/tmp/other/other_eurogard"
OPENVPN_CERTS_FOLDER = "/etc/openvpn/client"
MOUNT_PATH = "/mnt/usb/"
GPG_KEY_ID = "backup@eurogard.de"
LOGFILE_PATH = "/app/restore.log"

argParser = argparse.ArgumentParser(exit_on_error=False)
argParser.add_argument("-u", action="store_true", dest="usb", default=False)
try:
    args, unknown = argParser.parse_known_args()
except:
    pass
    

logContent = ""

def createLogEntry(entry:str):
    currentTime = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    logLine = f"[{currentTime}] | {entry}\n"
    os.system(f"logger -t EurogardBackup '{entry}'")
    return logLine

def failCleanupExit(errContent):
    global logContent
    try:
        #os.system("systemctl start eurogardvpn")
        os.system("led modem red")
        os.system("led modem flash")
        tmpdir.cleanup()
        #shutil.rmtree(tmpdir, True)
        if not args.usb:
            os.remove(encryptedBackupTarFile)   
    except: pass
    logContent += createLogEntry(f"AN ERROR OCCURED:")
    logContent += createLogEntry(errContent)
    with open(LOGFILE_PATH, "w") as logFile:
        logFile.write(logContent)
    if args.usb:
        with open(f"{MOUNT_PATH}done.log", "a") as logFile:
            logFile.write(logContent)
    sys.exit(1)


#os.system(f"logger -t EurogardBackup 'args {args}'")

# Create Eurogard data folder if it doesn't exist
Path(EUROGARD_DATA_FOLDER).mkdir(parents=True, exist_ok=True)

if args.usb:
    UPLOAD_FOLDER = "/mnt/usb"
# Get latest tar file in /tmp/upload dir
logContent += createLogEntry(f"Searching for encrypted backup archive in {UPLOAD_FOLDER}")
uploadedEncryptedTarFiles = list(filter(os.path.isfile, glob.glob(UPLOAD_FOLDER + "/*.gpg")))
uploadedEncryptedTarFiles.sort(key=lambda x: os.path.getmtime(x))

if len(uploadedEncryptedTarFiles) == 0:
    failCleanupExit(f"No archive found in {UPLOAD_FOLDER}")

encryptedBackupTarFile = uploadedEncryptedTarFiles[0]
logContent += createLogEntry(f"Found {len(uploadedEncryptedTarFiles)} archive(s) in {UPLOAD_FOLDER}. Using {encryptedBackupTarFile}")

# Decrypt tar
tmpdir = tempfile.TemporaryDirectory()
logContent += createLogEntry(f"Decrypting to {tmpdir.name}/decrypted.tgz")
decrytProc = subprocess.run(f"gpg --output {tmpdir.name}/decrypted.tgz --batch --pinentry-mode loopback --passphrase eurogard2023 -F /usr/share/eurogard/certs/eurogard_backup_priv_key.asc --decrypt '{encryptedBackupTarFile}'", shell=True, capture_output=True)
if decrytProc.returncode != 0:
    failCleanupExit(f"Decrypting failed with error: {decrytProc.stderr.decode()}")
    
backupTarFile = f"{tmpdir.name}/decrypted.tgz"

# Unpack tar
logContent += createLogEntry(f"Unpacking to {tmpdir.name}")
try:
    tarFile = tarfile.open(backupTarFile)
    tarFile.extractall(path=tmpdir.name)
    tarFile.close()
except Exception as e:
    failCleanupExit(f"Unpacking failed with error {e}")
# Check tar structure validity
logContent += createLogEntry(f"Verifying validity of tar contents")
extractedFiles = os.scandir(tmpdir.name)

backupRoot = glob.glob(f"{tmpdir.name}/eurogard")[0]
if backupRoot is None or "eurogard" not in backupRoot:
    failCleanupExit(f"Could not find eurogard folder at root of the archive")

backupRootFiles = [f for f in os.scandir(backupRoot) if f.is_file()]
backupRootFolders = [f for f in os.scandir(backupRoot) if f.is_dir()]

try:
    backupConfig = next(filter(lambda f: f.name == "config.xml", backupRootFiles))
    backupCertsFolder = next(filter(lambda f: f.name == "certs", backupRootFolders))
except:
    failCleanupExit(f"Could not find config.xml or certs folder in eurogard directory")
    
backupCertsFiles = os.scandir(backupCertsFolder.path)
os.system("ledd marquee&")
# Read config xml and get new lan ip address
logContent += createLogEntry(f"Retrieving IP address of ethernet interface from config.xml")
newIP = ""
ipFromXml = ""
try:
    tree = ET.parse(backupConfig.path)
    ipFromXml = tree.find("./lan_links/link/ip4_setting/ip4_addrs/ip4_addr").text
except Exception as e:
    failCleanupExit(f"Error while retrieving ip address from config xml. Error: {e}")
if ipFromXml != "":
    newIP = ipFromXml.split("/")[0]
    
logContent += createLogEntry(f"Found new IP: {newIP}")
saveIpProc = subprocess.run(f"usi set eurogard.new_ip {newIP}", shell=True)

os.system("systemctl stop eurogardcore")

# Import config.xml
logContent += createLogEntry(f"Importing config.xml")
importProc = subprocess.run(f"uci import {backupConfig.path}", shell=True, capture_output=True)
if importProc.returncode != 0:
    failCleanupExit(f"Error while importing config.xml: {importProc.stderr.decode()}")
if args.usb:
    commitProc = subprocess.run(f"uci commit", shell=True, capture_output=True)
    if commitProc.returncode != 0:
        failCleanupExit(f"Error while importing config.xml: {commitProc.stderr.decode()}")
    

# Clear old data from /data/eurogard directory
logContent += createLogEntry(f"Cleaning up old data in directories")
shutil.rmtree(EUROGARD_CERTS_FOLDER)
Path(EUROGARD_CERTS_FOLDER).mkdir(parents=True, exist_ok=True)

# Clear old data from /tmp/other/other_eurogard directory
shutil.rmtree(TMP_EUROGARD_CERTS_FOLDER)
Path(TMP_EUROGARD_CERTS_FOLDER).mkdir(parents=True, exist_ok=True)

# Clear old data from /tmp/other/other_eurogard directory
shutil.rmtree(OPENVPN_CERTS_FOLDER)
Path(OPENVPN_CERTS_FOLDER).mkdir(parents=True, exist_ok=True)

# Copy over certificates to /data/eurogard/certs (and to /tmp/other)
logContent += createLogEntry(f"Importing certificates")
for cert in backupCertsFiles:
    oldPath = cert.path
    newPath = f"{EUROGARD_CERTS_FOLDER}/{cert.name}"
    newPathTmp = f"{TMP_EUROGARD_CERTS_FOLDER}/{cert.name}"
    shutil.copy(oldPath, newPath)
    shutil.copy(oldPath, newPathTmp)

# Delete unpacked temp files
logContent += createLogEntry(f"Cleanup temporary files")
shutil.rmtree(tmpdir, True)

# Restart eurogardvpn service
# os.system("systemctl restart eurogardvpn")
# time.sleep(5)
# Delete tar
if not args.usb:
    os.remove(encryptedBackupTarFile)

logContent += createLogEntry(f"Backup succesfully restored!")
logContent += createLogEntry(f"The router will now be available under the following IP address: {newIP}")
logContent += createLogEntry(f"Please restart now")

with open(LOGFILE_PATH, "w") as logFile:
        logFile.write(logContent)

if args.usb:
    with open(f"{MOUNT_PATH}done.log", "a") as logFile:
        logFile.write(logContent)
        
    os.system("reboot")

sys.exit(0)
