#!/usr/bin/python3

from datetime import datetime
from pathlib import Path
import glob
import os
import shutil
import sys
import time
import crypt
import spwd
import subprocess
import tarfile
from hmac import compare_digest as compare_hash

import setproctitle

MOUNT_PATH = "/mnt/usb/"
UPLOAD_FOLDER = "/tmp/upload"
setproctitle.setproctitle("EurogardBackup")

logContent = ""

def isPathWriteable(path):
    if os.path.exists(path):
        # path exists
        if os.path.isfile(path): # is it a file or a dir?
            # also works when file is a link and the target is writable
            return os.access(path, os.W_OK)
        else:
            return False # path is a dir, so cannot write as a file
    # target does not exist, check perms on parent dir
    pdir = os.path.dirname(path)
    if not pdir: pdir = '.'
    # target is creatable if parent dir is writable
    return os.access(pdir, os.W_OK)

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

def failExit(errContent:str):
    print(errContent)
    global logContent
    os.system("led modem red")
    os.system("led modem flash")
    logContent += createLogEntry(f"AN ERROR OCCURED:")
    logContent += createLogEntry(errContent)
    if isPathWriteable(f"{MOUNT_PATH}done.log"):
        with open(f"{MOUNT_PATH}done.log", "w") as logFile:
            logFile.write(logContent)
    sys.exit(1)
    
def commitChanges():
    commitProc = subprocess.run(f"uci commit", shell=True, capture_output=True)
    if commitProc.returncode != 0:
        failExit(f"Error while importing config.xml: {commitProc.stderr.decode()}")
    # Remember this config as last known good (validated by the script)
    subprocess.run("/usr/scripts/eurogard_check_default_conf --refresh-good", shell=True, capture_output=True)
    
def triggerEventChanged():
    rmsgProc = subprocess.run('rmsg eventd cmd report event config_changed data "via web manager"', shell=True, capture_output=True)
    if rmsgProc.returncode != 0:
        failExit(f"Error while importing config.xml: {rmsgProc.stderr.decode()}")

# Check if usb drive is actually available

retryCounter = 0
while True:
    if os.path.exists(MOUNT_PATH) and os.path.ismount(MOUNT_PATH):
        os.system("echo 'Found mounted usb drive' | systemd-cat")
        logContent += createLogEntry(f"USB drive mounted. Checking if everything is in order")
        break
    else:
        os.system("echo 'Recently plugged in usb drive not yet mounted' | systemd-cat")
        time.sleep(1)
        retryCounter += 1
        if retryCounter >= 9:
            os.system("echo 'Exiting after 10 tries' | systemd-cat")
            sys.exit(1)
            

# Update by USB stick: a folder "update" holds the offline update bundle. Handled completely by eurogard_usb_update
# (LEDs, log on the stick, restart after the stick is pulled), before the password and the red LED of the import below
if os.path.isdir(f"{MOUNT_PATH}update"):
    os.system("echo 'Update folder found on usb drive' | systemd-cat")
    # Its own unit: this service Requires the mount of the stick and is stopped with it when the stick is pulled, the
    # update has to outlive that (it waits for the stick to be pulled and restarts the router afterwards)
    subprocess.run("systemctl reset-failed eurogard-usb-update.service > /dev/null 2>&1; "
                   "systemd-run --unit=eurogard-usb-update --collect --no-block /usr/scripts/eurogard_usb_update", shell=True)
    sys.exit(0)

fleetFilePaths = [f"{MOUNT_PATH}fleet.txt", f"{MOUNT_PATH}fleet", f"{MOUNT_PATH}fleetservice.txt", f"{MOUNT_PATH}fleetservice"]
fleetFileFound = False
for fleetFilePath in fleetFilePaths:
    if os.path.exists(fleetFilePath):
        fleetFileFound = True
        os.system("/usr/scripts/eurogard_provision_fleet")
        sys.exit(0)
    
# Check for existence of password file
passwordFilePath = f"{MOUNT_PATH}password"
logContent += createLogEntry(f"Checking if password file exists {passwordFilePath}")
passwordFileExists = os.path.exists(passwordFilePath)

if not passwordFileExists:
    # Password file not found, ignoring usb drive
    failExit("Could not find password file on usb drive.")
    
    
# Check for done file of previous restore procedure
doneFilePath = f"{MOUNT_PATH}done.log"
if os.path.exists(doneFilePath):
    failExit("This usb drive has been previuously used. Please remove the done file at the root of the drive to reuse this drive.")
# Check if the provided password is valid
logContent += createLogEntry(f"Checking if password is valid")
passwordFromFile = ""
with open(passwordFilePath, 'r') as passwordFile:
    passwordFromFile = passwordFile.read()
    passwordFromFile = passwordFromFile.strip()

if passwordFromFile == "":
    failExit("Password file is empty.")
    
encryptedPasswd = spwd.getspnam("admin")[1]
validPassword = compare_hash(crypt.crypt(passwordFromFile, encryptedPasswd), encryptedPasswd)

if not validPassword:
    failExit("Password provided in file is invalid.")

# Check for existence of an encrypted backup gpg file
logContent += createLogEntry(f"Looking for encrypted tar file on usb drive")
encryptedTarFilesOnUSB = list(filter(os.path.isfile, glob.glob(MOUNT_PATH + "*.gpg")))
encryptedTarFilesOnUSB.sort(key=lambda x: os.path.getmtime(x))

configFolderPath = f"{MOUNT_PATH}config"
configFolderImport = False

if len(encryptedTarFilesOnUSB) == 0:
    logContent += createLogEntry(f"Tar file not found, looking for config folder instead")
    if os.path.exists(configFolderPath):
        logContent += createLogEntry(f"Found config config folder continuing with inital setup.")
        configFolderImport = True
    else:
        failExit("No archive found on usb drive. Please make sure that the file ends with .gpg")

#chosenEncryptedBackupTarFile = encryptedTarFilesOnUSB[0]

logContent += createLogEntry(f"Usb drive looks good. Starting restore procedure")
# Call eurogard_import_backup_tar to handle restoring
#shutil.copy(chosenEncryptedBackupTarFile, f"{UPLOAD_FOLDER}/{os.path.basename(chosenEncryptedBackupTarFile)}")

if configFolderImport:
    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"
    # Get all files in config dir
    backupRootFiles = [f for f in os.scandir(configFolderPath) if f.is_file()]
    backupRootFolders = [f for f in os.scandir(configFolderPath) if f.is_dir()]
    backupCertsFiles = glob.glob(configFolderPath + "/*/*.tar")
    os.system("ledd marquee&")
    
    # First find active vpns
    logContent += createLogEntry(f"Checking if any vpn is still active")
    vpn1ActiveId = subprocess.run("awk '/vpn1_tunnel/,/}/' /var/config/eurogard | grep -C 2 'enable = true' | grep 'id' | awk '{print $3}'", capture_output=True, text=True, shell=True).stdout.strip()
    vpn2ActiveId = subprocess.run("awk '/vpn2_tunnel/,/}/' /var/config/eurogard | grep -C 2 'enable = true' | grep 'id' | awk '{print $3}'", capture_output=True, text=True, shell=True).stdout.strip()
    
    configChanged = False
    
    if vpn1ActiveId is not None and vpn1ActiveId != "":
        logContent += createLogEntry(f"Disabling vpn id {vpn1ActiveId} on vpn1")
        subprocess.run(f"uci set eurogard.vpn1_tunnel[{vpn1ActiveId}].enable 'false'", capture_output=True, text=True, shell=True)
        configChanged = True
    if vpn2ActiveId is not None and vpn2ActiveId != "":
        logContent += createLogEntry(f"Disabling vpn id {vpn2ActiveId} on vpn1")
        subprocess.run(f"uci set eurogard.vpn2_tunnel[{vpn2ActiveId}].enable 'false'", capture_output=True, text=True, shell=True)
        configChanged = True
    
    if configChanged:
        commitChanges()
        triggerEventChanged()
        # Wait for processes to stop
        time.sleep(10)
        
    
    # Second import vpn files
    # Clear old data from /data/eurogard directory
    logContent += createLogEntry(f"Cleaning up old data in directories")
    
    
    # try:
    #     shutil.rmtree(EUROGARD_CERTS_FOLDER)
    # except:
    #     pass
    # Path(EUROGARD_CERTS_FOLDER).mkdir(parents=True, exist_ok=True)

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

    # # Clear old data from /tmp/other/other_eurogard directory
    # try:
    #     shutil.rmtree(OPENVPN_CERTS_FOLDER)
    # except:
    #     pass
    # Path(OPENVPN_CERTS_FOLDER).mkdir(parents=True, exist_ok=True)
    
    commitChanges()
    triggerEventChanged()

    time.sleep(5)
    
    # Look for config xml
    try:
        backupConfig = next(filter(lambda f: f.name == "config.xml", backupRootFiles))
        logContent += createLogEntry(f"Importing config.xml")
        importProc = subprocess.run(f"uci import {backupConfig.path}", shell=True, capture_output=True)
        if importProc.returncode != 0:
            failExit(f"Error while importing config.xml: {importProc.stderr.decode()}")
        commitChanges()
    except:
        logContent += createLogEntry(f"config.xml not found, skipping")
        
    time.sleep(5)
    
    # Copy over certificates to /data/eurogard/certs (and to /tmp/other)
    logContent += createLogEntry(f"Importing certificates")
    for cert in backupCertsFiles:
        certName = os.path.basename(cert)
        oldPath = cert
        newPath = f"{EUROGARD_CERTS_FOLDER}/{certName}"
        newPathTmp = f"{TMP_EUROGARD_CERTS_FOLDER}/{certName}"
        shutil.copy(oldPath, newPath)
        shutil.copy(oldPath, newPathTmp)
        
    commitChanges()
    triggerEventChanged()
    
    time.sleep(5)
    # Get name of active vpns
    vpn1Files = glob.glob(configFolderPath + "/vpn1/*.tar")
    vpn2Files = glob.glob(configFolderPath + "/vpn2/*.tar")
    
    if len(vpn1Files) == 1:
        vpn1Name = Path(vpn1Files[0]).stem
        try:
            newTar = tarfile.open(vpn1Files[0])
            ovpnFile = next(x for x in newTar.getmembers() if os.path.splitext(x.name)[1] == ".ovpn")
            vpn1Name = Path(ovpnFile.path).stem
        except:
            failExit("Error while importing certificates")
        # Search for id
        vpn1Id = subprocess.run("awk '/vpn1_tunnel/,/}/' /var/config/eurogard | grep -C 2 'name = " + vpn1Name + "' | grep 'id' | awk '{print $3}'", capture_output=True, text=True, shell=True).stdout.strip()
        if vpn1Id is None or vpn1Id == "":
            logContent += createLogEntry(f"VPN with name {vpn1Name} not found in list. Something is wrong")
        else:
            logContent += createLogEntry(f"Activating {vpn1Name} for vpn1")
            subprocess.run(f"uci set eurogard.vpn1_tunnel[{vpn1Id}].enable 'true'", capture_output=True, text=True, shell=True)
    
    if len(vpn2Files) == 1:
        vpn2Name = Path(vpn2Files[0]).stem
        try:
            newTar = tarfile.open(vpn2Files[0])
            ovpnFile = next(x for x in newTar.getmembers() if os.path.splitext(x.name)[1] == ".ovpn")
            vpn2Name = Path(ovpnFile.path).stem
        except:
            failExit("Error while importing certificates")
        # Search for id
        vpn2Id = subprocess.run("awk '/vpn1_tunnel/,/}/' /var/config/eurogard | grep -C 2 'name = " + vpn2Name + "' | grep 'id' | awk '{print $3}'", capture_output=True, text=True, shell=True).stdout.strip()
        if vpn2Id is None or vpn2Id == "":
            logContent += createLogEntry(f"VPN with name {vpn2Name} not found in list. Something is wrong")
        else:
            logContent += createLogEntry(f"Activating {vpn2Name} for vpn2")
            subprocess.run(f"uci set eurogard.vpn2_tunnel[{vpn2Id}].enable 'true'", capture_output=True, text=True, shell=True)
    
    commitChanges()
    triggerEventChanged()

if isPathWriteable(doneFilePath):
    with open(doneFilePath, "w") as logFile:
            logFile.write(logContent)
            
if configFolderImport:
    os.system("reboot")
else:
    os.system("/usr/scripts/eurogard_import_backup_tar -u")
