#!/usr/bin/env python
# -*- coding: utf-8 -*-
# +--------------------------------------------------------------------------+
# | OpenFW UTM Community                                                          |
# +--------------------------------------------------------------------------+

import os
import sys
import subprocess
import tempfile
import socket
from datetime import datetime

SWROOT = "/var/efw"
CONF_FILE = SWROOT + "/external-backups/settings"
BASE_PATH = "/var/efw/external-backups"
CRON_FILE = "/etc/cron.d/external-backups"
LOG_FILE = "/var/log/messages"

INCLUDE_SOURCE = "/var/efw/external-backups/include"
INCLUDE_TARGET = "/usr/lib/efw/backup/include.system"

BACKUP_TYPE = ""
MEGA_MIRROR = "off"
FTP_MIRROR = "off"
SFTP_MIRROR = "off"
SMB_MIRROR = "off"
GDRIVE_MIRROR = "off"

BACKUP_MAIL = "off"
USE_EMAILRELAY = "off"
EMAIL_CRON_MIM = "*"
EMAIL_CRON_HOR = "*"
EMAIL_CRON_DIA_MES = "*"
EMAIL_CRON_MES = "*"
EMAIL_CRON_DIA_SEM = "*"
BACKUP_RCPTTO = ""
BACKUP_MAILFROM = ""
SMTP_SERVER = ""
SMTP_PORT = "587"
SMTP_AUTH = "off"
SMTP_USER = ""
SMTP_PASS = ""
ENCRYPTION = "tls"

NOTIFY_ENABLED = "off"
NOTIFY_USE_EMAILRELAY = "off"
NOTIFY_USE_EMAIL_BACKUP = "off"
NOTIFY_SMTP_SERVER = ""
NOTIFY_SMTP_PORT = "587"
NOTIFY_SMTP_AUTH = "off"
NOTIFY_SMTP_USER = ""
NOTIFY_SMTP_PASS = ""
NOTIFY_ENCRYPTION = "tls"
NOTIFY_FROM = ""
NOTIFY_TO = ""
NOTIFY_SUCCESS = "off"
NOTIFY_FAILURE = "off"
NOTIFY_SUBJECT_PREFIX = "[OpenFW Backup]"

MEGA_ENABLED = "off"
MEGA_USER = ""
MEGA_PASSWORD = ""
MEGA_DIR = ""

FTP_ENABLED = "off"
FTP_HOST = ""
FTP_USER = ""
FTP_PASSWORD = ""
FTP_DIR = ""
FTP_PORT = "21"
FTP_PASSIVE = "off"

SFTP_ENABLED = "off"
SFTP_HOST = ""
SFTP_USER = ""
SFTP_PASSWORD = ""
SFTP_DIR = ""
SFTP_PORT = "22"

SMB_ENABLED = "off"
SMB_HOST = ""
SMB_DOMAIN = ""
SMB_USER = ""
SMB_PASSWORD = ""
SMB_DIR = ""

GDRIVE_ENABLED = "off"
GDRIVE_DIR = "CONFIGS"

LOCAL_BACKUP_DIR = "/var/backups/"

if not os.path.exists(BASE_PATH):
    os.makedirs(BASE_PATH)


def append_include_file():
    """Appends the content of the include file to the end of include.system"""
    if os.path.isfile(INCLUDE_SOURCE):
        try:
            with open(INCLUDE_SOURCE, "r") as src:
                content = src.read()
            with open(INCLUDE_TARGET, "a") as dst:
                dst.write(content)
        except Exception:
            pass


def load_config():
    global BACKUP_TYPE
    global MEGA_ENABLED, MEGA_MIRROR, MEGA_USER, MEGA_PASSWORD, MEGA_DIR
    global FTP_ENABLED, FTP_MIRROR, FTP_HOST, FTP_USER, FTP_PASSWORD, FTP_DIR, FTP_PORT, FTP_PASSIVE
    global SFTP_ENABLED, SFTP_MIRROR, SFTP_HOST, SFTP_USER, SFTP_PASSWORD, SFTP_DIR, SFTP_PORT
    global SMB_ENABLED, SMB_MIRROR, SMB_HOST, SMB_DOMAIN, SMB_USER, SMB_PASSWORD, SMB_DIR
    global GDRIVE_ENABLED, GDRIVE_MIRROR, GDRIVE_DIR
    global BACKUP_MAIL, USE_EMAILRELAY, BACKUP_RCPTTO, BACKUP_MAILFROM, SMTP_SERVER, SMTP_PORT, SMTP_AUTH, SMTP_USER, SMTP_PASS, ENCRYPTION, EMAIL_CRON_MIM, EMAIL_CRON_HOR, EMAIL_CRON_DIA_MES, EMAIL_CRON_MES, EMAIL_CRON_DIA_SEM
    global NOTIFY_ENABLED, NOTIFY_USE_EMAILRELAY, NOTIFY_USE_EMAIL_BACKUP, NOTIFY_SMTP_SERVER, NOTIFY_SMTP_PORT, NOTIFY_SMTP_AUTH, NOTIFY_SMTP_USER, NOTIFY_SMTP_PASS, NOTIFY_ENCRYPTION, NOTIFY_FROM, NOTIFY_TO, NOTIFY_SUCCESS, NOTIFY_FAILURE, NOTIFY_SUBJECT_PREFIX

    if os.path.isfile(CONF_FILE):
        with open(CONF_FILE, "r") as f:
            for line in f:
                if "=" in line:
                    key, value = line.split("=", 1)
                    key = key.replace("\r", "").strip()
                    value = value.replace("\r", "").strip()
                    if not key:
                        continue

                    if key == "BACKUP_TYPE":
                        BACKUP_TYPE = value
                    elif key == "MEGA_ENABLED":
                        MEGA_ENABLED = value
                    elif key == "MEGA_MIRROR":
                        MEGA_MIRROR = value
                    elif key == "MEGA_USER":
                        MEGA_USER = value
                    elif key == "MEGA_PASSWORD":
                        MEGA_PASSWORD = value
                    elif key == "MEGA_DIR":
                        MEGA_DIR = value
                    elif key == "FTP_ENABLED":
                        FTP_ENABLED = value
                    elif key == "FTP_MIRROR":
                        FTP_MIRROR = value
                    elif key == "FTP_HOST":
                        FTP_HOST = value
                    elif key == "FTP_USER":
                        FTP_USER = value
                    elif key == "FTP_PASSWORD":
                        FTP_PASSWORD = value
                    elif key == "FTP_DIR":
                        FTP_DIR = value
                    elif key == "FTP_PORT":
                        FTP_PORT = value
                    elif key == "FTP_PASSIVE":
                        FTP_PASSIVE = value
                    elif key == "SFTP_ENABLED":
                        SFTP_ENABLED = value
                    elif key == "SFTP_MIRROR":
                        SFTP_MIRROR = value
                    elif key == "SFTP_HOST":
                        SFTP_HOST = value
                    elif key == "SFTP_USER":
                        SFTP_USER = value
                    elif key == "SFTP_PASSWORD":
                        SFTP_PASSWORD = value
                    elif key == "SFTP_DIR":
                        SFTP_DIR = value
                    elif key == "SFTP_PORT":
                        SFTP_PORT = value
                    elif key == "SMB_ENABLED":
                        SMB_ENABLED = value
                    elif key == "SMB_MIRROR":
                        SMB_MIRROR = value
                    elif key == "SMB_HOST":
                        SMB_HOST = value
                    elif key == "SMB_DOMAIN":
                        SMB_DOMAIN = value
                    elif key == "SMB_USER":
                        SMB_USER = value
                    elif key == "SMB_PASSWORD":
                        SMB_PASSWORD = value
                    elif key == "SMB_DIR":
                        SMB_DIR = value
                    elif key == "GDRIVE_ENABLED":
                        GDRIVE_ENABLED = value
                    elif key == "GDRIVE_MIRROR":
                        GDRIVE_MIRROR = value
                    elif key == "GDRIVE_DIR":
                        GDRIVE_DIR = value
                    elif key == "BACKUP_MAIL":
                        BACKUP_MAIL = value
                    elif key == "USE_EMAILRELAY":
                        USE_EMAILRELAY = value
                    elif key == "BACKUP_RCPTTO":
                        BACKUP_RCPTTO = value
                    elif key == "BACKUP_MAILFROM":
                        BACKUP_MAILFROM = value
                    elif key == "SMTP_SERVER":
                        SMTP_SERVER = value
                    elif key == "SMTP_PORT":
                        SMTP_PORT = value
                    elif key == "SMTP_AUTH":
                        SMTP_AUTH = value
                    elif key == "SMTP_USER":
                        SMTP_USER = value
                    elif key == "SMTP_PASS":
                        SMTP_PASS = value
                    elif key == "ENCRYPTION":
                        ENCRYPTION = value
                    elif key == "EMAIL_CRON_MIM":
                        EMAIL_CRON_MIM = value
                    elif key == "EMAIL_CRON_HOR":
                        EMAIL_CRON_HOR = value
                    elif key == "EMAIL_CRON_DIA_MES":
                        EMAIL_CRON_DIA_MES = value
                    elif key == "EMAIL_CRON_MES":
                        EMAIL_CRON_MES = value
                    elif key == "EMAIL_CRON_DIA_SEM":
                        EMAIL_CRON_DIA_SEM = value
                    elif key == "NOTIFY_ENABLED":
                        NOTIFY_ENABLED = value
                    elif key == "NOTIFY_USE_EMAILRELAY":
                        NOTIFY_USE_EMAILRELAY = value
                    elif key == "NOTIFY_USE_EMAIL_BACKUP":
                        NOTIFY_USE_EMAIL_BACKUP = value
                    elif key == "NOTIFY_SMTP_SERVER":
                        NOTIFY_SMTP_SERVER = value
                    elif key == "NOTIFY_SMTP_PORT":
                        NOTIFY_SMTP_PORT = value
                    elif key == "NOTIFY_SMTP_AUTH":
                        NOTIFY_SMTP_AUTH = value
                    elif key == "NOTIFY_SMTP_USER":
                        NOTIFY_SMTP_USER = value
                    elif key == "NOTIFY_SMTP_PASS":
                        NOTIFY_SMTP_PASS = value
                    elif key == "NOTIFY_ENCRYPTION":
                        NOTIFY_ENCRYPTION = value
                    elif key == "NOTIFY_FROM":
                        NOTIFY_FROM = value
                    elif key == "NOTIFY_RCPTTO":
                        NOTIFY_TO = value
                    elif key == "NOTIFY_SUCCESS":
                        NOTIFY_SUCCESS = value
                    elif key == "NOTIFY_FAILURE":
                        NOTIFY_FAILURE = value
                    elif key == "NOTIFY_SUBJECT_PREFIX":
                        NOTIFY_SUBJECT_PREFIX = value


def get_cron_value(prefix, field):
    val = ""
    target_key = "%s_CRON_%s" % (prefix, field)
    if os.path.isfile(CONF_FILE):
        with open(CONF_FILE, "r") as f:
            for line in f:
                if line.startswith(target_key + "="):
                    val = line.split("=", 1)[1].replace("\r", "").strip()
                    break

    if not val or "|" in val:
        return "*"
    return val


def obscure_password(plaintext):
    try:
        devnull = open(os.devnull, 'w')
        p = subprocess.Popen(["rclone", "obscure", plaintext], stdout=subprocess.PIPE, stderr=devnull)
        out, _ = p.communicate()
        devnull.close()
        return out.replace("\n", "").replace("\r", "")
    except Exception:
        return ""


def generate_mega_conf():
    conf_path = BASE_PATH + "/mega.conf"
    if MEGA_ENABLED == "on" and MEGA_USER and MEGA_PASSWORD:
        obscured_pass = obscure_password(MEGA_PASSWORD)
        content = "[mega]\ntype = mega\nuser = %s\npass = %s\n" % (MEGA_USER, obscured_pass)
        with open(conf_path, "w") as f:
            f.write(content)
        os.chmod(conf_path, 0600)
    else:
        if os.path.exists(conf_path):
            os.remove(conf_path)


def generate_ftp_conf():
    conf_path = BASE_PATH + "/ftp.conf"
    if FTP_ENABLED == "on" and FTP_HOST:
        obscured_pass = obscure_password(FTP_PASSWORD)
        content = "[ftp]\ntype = ftp\nhost = %s\nport = %s\nuser = %s\npass = %s\n" % (FTP_HOST, FTP_PORT, FTP_USER, obscured_pass)
        with open(conf_path, "w") as f:
            f.write(content)
        os.chmod(conf_path, 0600)
    else:
        if os.path.exists(conf_path):
            os.remove(conf_path)


def generate_sftp_conf():
    conf_path = BASE_PATH + "/sftp.conf"
    if SFTP_ENABLED == "on" and SFTP_HOST:
        obscured_pass = obscure_password(SFTP_PASSWORD)
        content = "[sftp]\ntype = sftp\nhost = %s\nport = %s\nuser = %s\npass = %s\n" % (SFTP_HOST, SFTP_PORT, SFTP_USER, obscured_pass)
        with open(conf_path, "w") as f:
            f.write(content)
        os.chmod(conf_path, 0600)
    else:
        if os.path.exists(conf_path):
            os.remove(conf_path)


def generate_smb_conf():
    conf_path = BASE_PATH + "/smb.conf"
    if SMB_ENABLED == "on" and SMB_HOST and SMB_DIR:
        obscured_pass = obscure_password(SMB_PASSWORD)
        content = "[smb]\ntype = smb\nhost = %s\nuser = %s\npass = %s\ndomain = %s\n" % (SMB_HOST, SMB_USER, obscured_pass, SMB_DOMAIN)
        with open(conf_path, "w") as f:
            f.write(content)
        os.chmod(conf_path, 0600)
    else:
        if os.path.exists(conf_path):
            os.remove(conf_path)


def generate_gdrive_conf():
    token_file = BASE_PATH + "/gdrive-token.json"
    conf_file = BASE_PATH + "/gdrive.conf"

    if os.path.isfile(token_file) and os.path.getsize(token_file) > 0:
        need_generate = False
        if not os.path.isfile(conf_file):
            need_generate = True
        else:
            if os.path.getmtime(token_file) > os.path.getmtime(conf_file):
                need_generate = True

        if need_generate:
            with open(token_file, "r") as f:
                raw_token = f.read().replace("\n", "").replace("\r", "")

            if raw_token:
                content = "[gdrive]\ntype = drive\nscope = drive\ntoken = %s\n" % raw_token
                with open(conf_file, "w") as f:
                    f.write(content)
                os.chmod(conf_file, 0600)


def update_cron():
    lines = ["# Auto-generated by external-backups script. Do not edit directly.\n"]

    if MEGA_ENABLED == "on":
        cron_time = "%s %s %s %s %s" % (
            get_cron_value('MEGA', 'MIM'),
            get_cron_value('MEGA', 'HOR'),
            get_cron_value('MEGA', 'DIA_MES'),
            get_cron_value('MEGA', 'MES'),
            get_cron_value('MEGA', 'DIA_SEM')
        )
        lines.append("%s root /usr/local/bin/external-backups --mega-cron\n" % cron_time)

    if FTP_ENABLED == "on":
        cron_time = "%s %s %s %s %s" % (
            get_cron_value('FTP', 'MIM'),
            get_cron_value('FTP', 'HOR'),
            get_cron_value('FTP', 'DIA_MES'),
            get_cron_value('FTP', 'MES'),
            get_cron_value('FTP', 'DIA_SEM')
        )
        lines.append("%s root /usr/local/bin/external-backups --ftp-cron\n" % cron_time)

    if SFTP_ENABLED == "on":
        cron_time = "%s %s %s %s %s" % (
            get_cron_value('SFTP', 'MIM'),
            get_cron_value('SFTP', 'HOR'),
            get_cron_value('SFTP', 'DIA_MES'),
            get_cron_value('SFTP', 'MES'),
            get_cron_value('SFTP', 'DIA_SEM')
        )
        lines.append("%s root /usr/local/bin/external-backups --sftp-cron\n" % cron_time)

    if SMB_ENABLED == "on":
        cron_time = "%s %s %s %s %s" % (
            get_cron_value('SMB', 'MIM'),
            get_cron_value('SMB', 'HOR'),
            get_cron_value('SMB', 'DIA_MES'),
            get_cron_value('SMB', 'MES'),
            get_cron_value('SMB', 'DIA_SEM')
        )
        lines.append("%s root /usr/local/bin/external-backups --smb-cron\n" % cron_time)

    if GDRIVE_ENABLED == "on":
        cron_time = "%s %s %s %s %s" % (
            get_cron_value('GDRIVE', 'MIM'),
            get_cron_value('GDRIVE', 'HOR'),
            get_cron_value('GDRIVE', 'DIA_MES'),
            get_cron_value('GDRIVE', 'MES'),
            get_cron_value('GDRIVE', 'DIA_SEM')
        )
        lines.append("%s root /usr/local/bin/external-backups --gdrive-cron\n" % cron_time)
    if BACKUP_MAIL == "on":
        cron_time = "%s %s %s %s %s" % (
            EMAIL_CRON_MIM if EMAIL_CRON_MIM else "*",
            EMAIL_CRON_HOR if EMAIL_CRON_HOR else "*",
            EMAIL_CRON_DIA_MES if EMAIL_CRON_DIA_MES else "*",
            EMAIL_CRON_MES if EMAIL_CRON_MES else "*",
            EMAIL_CRON_DIA_SEM if EMAIL_CRON_DIA_SEM else "*"
        )
        lines.append("%s root /usr/local/bin/external-backups --email-cron\n" % cron_time)


    with open(CRON_FILE, "w") as f:
        f.writelines(lines)

    os.chmod(CRON_FILE, 0644)
    devnull = open(os.devnull, 'w')
    subprocess.call("/etc/init.d/fcron restart", shell=True, stdout=devnull, stderr=devnull)
    devnull.close()


def write_log(msg):
    timestamp = datetime.now().strftime("%b %d %H:%M:%S")
    hostname = socket.gethostname().split(".")[0]
    pid = os.getpid()
    log_entry = "%s %s backup[%d]: %s\n" % (timestamp, hostname, pid, msg)
    with open(LOG_FILE, "a") as f:
        f.write(log_entry)


def run_rclone_backup(protocol, remote_dir, conf_filename, mirror="off"):
    action = "sync" if mirror == "on" else "copy"
    conf_path = "%s/%s" % (BASE_PATH, conf_filename)

    tmp = tempfile.NamedTemporaryFile("w+", delete=False)
    rclone_log_path = tmp.name
    tmp.close()

    cmd = [
        "rclone", action, LOCAL_BACKUP_DIR, "%s:%s" % (protocol, remote_dir),
        "--config", conf_path, "--log-level", "NOTICE"
    ]

    devnull = open(os.devnull, 'w')
    err_file = open(rclone_log_path, "w")
    res = subprocess.call(cmd, stdout=devnull, stderr=err_file)
    devnull.close()
    err_file.close()

    status = res

    if os.path.exists(rclone_log_path) and os.path.getsize(rclone_log_path) > 0:
        with open(rclone_log_path, "r") as err_file:
            for line in err_file:
                line = line.strip()
                if line:
                    write_log("rclone: %s" % line)

    if os.path.exists(rclone_log_path):
        os.remove(rclone_log_path)

    return status == 0


def do_mega_backup():
    if MEGA_ENABLED != "on" or not os.path.isfile(BASE_PATH + "/mega.conf"):
        return False
    return run_rclone_backup("mega", MEGA_DIR, "mega.conf", MEGA_MIRROR)


def do_ftp_backup():
    if FTP_ENABLED != "on" or not os.path.isfile(BASE_PATH + "/ftp.conf"):
        return False
    return run_rclone_backup("ftp", FTP_DIR, "ftp.conf", FTP_MIRROR)


def do_sftp_backup():
    if SFTP_ENABLED != "on" or not os.path.isfile(BASE_PATH + "/sftp.conf"):
        return False
    return run_rclone_backup("sftp", SFTP_DIR, "sftp.conf", SFTP_MIRROR)


def do_smb_backup():
    if SMB_ENABLED != "on" or not os.path.isfile(BASE_PATH + "/smb.conf"):
        return False
    return run_rclone_backup("smb", SMB_DIR, "smb.conf", SMB_MIRROR)


def do_gdrive_backup():
    if GDRIVE_ENABLED != "on" or not os.path.isfile(BASE_PATH + "/gdrive.conf"):
        return False
    return run_rclone_backup("gdrive", GDRIVE_DIR, "gdrive.conf", GDRIVE_MIRROR)

def sync_email_settings():
    backup_settings = "/var/efw/backup/settings"
    if not os.path.exists(os.path.dirname(backup_settings)):
        os.makedirs(os.path.dirname(backup_settings))
    # Read existing settings
    settings = {}
    if os.path.isfile(backup_settings):
        with open(backup_settings, "r") as f:
            for line in f:
                if "=" in line:
                    k, v = line.strip().split("=", 1)
                    settings[k] = v
    # Determine smarthost
    smarthost = SMTP_SERVER
    if USE_EMAILRELAY == "on":
        relay_file = "/var/openfw/emailrelay/settings"
        if os.path.isfile(relay_file):
            with open(relay_file, "r") as f:
                for line in f:
                    if "=" in line:
                        k, v = line.strip().split("=", 1)
                        if k in ("SMARTHOST_SERVER", "SMARTHOST", "SMTP_SERVER"):
                            smarthost = v.strip().strip("'").strip('"')
    # Update email settings
    settings["BACKUP_MAIL"] = BACKUP_MAIL
    settings["BACKUP_RCPTTO"] = BACKUP_RCPTTO
    settings["BACKUP_MAILFROM"] = BACKUP_MAILFROM
    settings["SMTP_SERVER"] = smarthost
    settings["BACKUP_SMARTHOST"] = smarthost
    settings["BACKUP_MAX_MAIL_SIZE"] = settings.get("BACKUP_MAX_MAIL_SIZE", "30")
    # Ensure backup includes settings by default if not already configured
    if "BACKUP_SETTINGS" not in settings:
        settings["BACKUP_SETTINGS"] = "on"
    # Write back
    with open(backup_settings, "w") as f:
        for k, v in settings.items():
            f.write("%s=%s\n" % (k, v))
    os.chmod(backup_settings, 0644)


def send_email_with_attachment(filepath, server, port, encryption, auth, user, passw, from_addr, to_addr, subject):
    """Send an email with a file attachment using smtplib with full SMTP config."""
    import smtplib
    import email
    from email import encoders
    from email.mime.base import MIMEBase
    from email.mime.multipart import MIMEMultipart
    from email.mime.text import MIMEText
    import socket
    import ssl

    try:
        # Build message
        msg = MIMEMultipart()
        msg['From'] = from_addr
        msg['To'] = to_addr
        msg['Subject'] = subject

        _ehost = socket.gethostname()
        _etime = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        body = """<html>
<body style="margin:0;padding:0;background:#ffffff;font-family:Arial,Helvetica,sans-serif;color:#000000;">
  <table width="100%%" cellpadding="0" cellspacing="0" style="background:#008100;">
    <tr><td style="padding:16px;color:#ffffff;font-size:18px;font-weight:bold;">OpenFW Backup</td></tr>
  </table>
  <table width="100%%" cellpadding="0" cellspacing="0" style="background:#ffffff;">
    <tr><td style="padding:20px;color:#000000;font-size:14px;">
      <p style="margin:0 0 12px 0;">Backup generated on <b>%s</b></p>
      <p style="margin:0 0 12px 0;">Host: <b>%s</b></p>
      <p style="margin:0;">Please find the attached backup archive.</p>
    </td></tr>
  </table>
</body>
</html>""" % (_etime, _ehost)
        msg.attach(MIMEText(body, 'html'))

        # Attach file
        if filepath and os.path.isfile(filepath):
            part = MIMEBase('application', 'octet-stream')
            with open(filepath, 'rb') as f:
                part.set_payload(f.read())
            encoders.encode_base64(part)
            filename = os.path.basename(filepath)
            part.add_header('Content-Disposition', 'attachment; filename="%s"' % filename)
            msg.attach(part)

        # Determine SMTP connection
        port = int(port) if port else 25
        if encryption == 'ssl':
            smtp = smtplib.SMTP_SSL(server, port, timeout=30)
        else:
            smtp = smtplib.SMTP(server, port, timeout=30)
            smtp.ehlo()
            if encryption == 'tls':
                smtp.starttls()
                smtp.ehlo()

        # Authenticate if needed
        if auth == 'on' and user:
            smtp.login(user, passw)

        # Send
        smtp.sendmail(from_addr, [to_addr], msg.as_string())
        smtp.quit()
        return True, "Email sent successfully to %s" % to_addr
    except Exception as e:
        return False, "Failed to send email: %s" % str(e)


def do_email_backup():
    if BACKUP_MAIL != "on":
        write_log("Email backup is disabled (BACKUP_MAIL=off).")
        return False

    # Sync email settings to backup settings (with BACKUP_MAIL=off so autbackup.sh generates but doesn't send)
    sync_email_settings()

    # Temporarily set BACKUP_MAIL=off in backup settings so autbackup.sh generates but doesn't send
    backup_settings = "/var/efw/backup/settings"
    settings = {}
    if os.path.isfile(backup_settings):
        with open(backup_settings, "r") as f:
            for line in f:
                if "=" in line:
                    k, v = line.strip().split("=", 1)
                    settings[k] = v
    settings["BACKUP_MAIL"] = "off"
    with open(backup_settings, "w") as f:
        for k, v in settings.items():
            f.write("%s=%s\n" % (k, v))
    os.chmod(backup_settings, 0644)

    write_log("Starting email backup: generating backup archive.")
    # Record existing backup files before generation
    backup_dir = "/var/backups/"
    existing_files = set()
    if os.path.isdir(backup_dir):
        for fn in os.listdir(backup_dir):
            if fn.startswith("backup-") and fn.endswith(".tar.gz"):
                existing_files.add(fn)

    # Log output to a file for debugging
    log_path = "/var/volatile/tmp/external-backups-email.out"
    err_path = "/var/volatile/tmp/external-backups-email.err"
    out_f = open(log_path, "w")
    err_f = open(err_path, "w")
    res = subprocess.call("/usr/local/bin/sendautobackup", stdout=out_f, stderr=err_f)
    out_f.close()
    err_f.close()

    # Log any errors from sendautobackup
    if os.path.exists(err_path) and os.path.getsize(err_path) > 0:
        with open(err_path, "r") as ef:
            for line in ef:
                line = line.strip()
                if line:
                    write_log("sendautobackup stderr: %s" % line)

    if res != 0:
        write_log("Backup generation failed with exit code %d." % res)
        return False

    # Find the newly generated backup file
    new_file = None
    if os.path.isdir(backup_dir):
        for fn in os.listdir(backup_dir):
            if fn.startswith("backup-") and fn.endswith(".tar.gz") and fn not in existing_files:
                new_file = os.path.join(backup_dir, fn)
                break
    # If no new file found, use the most recent one
    if not new_file:
        candidates = []
        if os.path.isdir(backup_dir):
            for fn in os.listdir(backup_dir):
                if fn.startswith("backup-") and fn.endswith(".tar.gz"):
                    full = os.path.join(backup_dir, fn)
                    candidates.append((os.path.getmtime(full), full))
        if candidates:
            candidates.sort(reverse=True)
            new_file = candidates[0][1]

    if not new_file or not os.path.isfile(new_file):
        write_log("No backup file found to send.")
        return False

    write_log("Backup generated: %s. Sending via email." % os.path.basename(new_file))

    # Restore BACKUP_MAIL=on in backup settings (for future reference)
    settings["BACKUP_MAIL"] = "on"
    with open(backup_settings, "w") as f:
        for k, v in settings.items():
            f.write("%s=%s\n" % (k, v))
    os.chmod(backup_settings, 0644)

    # Determine SMTP settings
    server = SMTP_SERVER
    port = SMTP_PORT if SMTP_PORT else "587"
    encryption = ENCRYPTION if ENCRYPTION else "tls"
    auth = SMTP_AUTH if SMTP_AUTH else "off"
    user = SMTP_USER
    passw = SMTP_PASS

    # If using EmailRelay, load settings from emailrelay
    if USE_EMAILRELAY == "on":
        relay_file = "/var/openfw/emailrelay/settings"
        if os.path.isfile(relay_file):
            with open(relay_file, "r") as f:
                for line in f:
                    if "=" in line:
                        k, v = line.strip().split("=", 1)
                        v = v.strip().strip("'").strip('"')
                        if k in ("SMARTHOST_SERVER", "SMARTHOST", "SMTP_SERVER"):
                            server = v
                        if k in ("SMARTHOST_PORT", "SMTP_PORT"):
                            port = v
                        if k == "SMARTHOST_TLS":
                            if v == "on":
                                encryption = "tls"
            # Load auth from emailrelay auth file
            auth_file = "/etc/emailrelay.auth"
            if os.path.isfile(auth_file):
                with open(auth_file, "r") as f:
                    for line in f:
                        line = line.strip()
                        if line.startswith("#") or not line:
                            continue
                        import re
                        m = re.match(r"client\s+(?:plain|login|auth)\s+(\S+)\s+(.+)", line, re.IGNORECASE)
                        if m:
                            user = m.group(1)
                            passw = m.group(2)
                            auth = "on"
                            break

    # Validate recipient
    if not BACKUP_RCPTTO:
        write_log("No recipient email address configured.")
        return False

    from_addr = BACKUP_MAILFROM if BACKUP_MAILFROM else "root@%s" % socket.gethostname().split(".")[0]
    subject = "Backup from %s - %s" % (socket.gethostname().split(".")[0], os.path.basename(new_file))

    # Send email with attachment
    ok, msg = send_email_with_attachment(
        new_file, server, port, encryption, auth, user, passw,
        from_addr, BACKUP_RCPTTO, subject)

    if ok:
        write_log("Email sent successfully: %s" % msg)
    else:
        write_log("Email sending failed: %s" % msg)

    return ok


def get_notify_smtp_settings():
    server = NOTIFY_SMTP_SERVER
    port = NOTIFY_SMTP_PORT if NOTIFY_SMTP_PORT else "587"
    encryption = NOTIFY_ENCRYPTION if NOTIFY_ENCRYPTION else "tls"
    auth = NOTIFY_SMTP_AUTH if NOTIFY_SMTP_AUTH else "off"
    user = NOTIFY_SMTP_USER
    passw = NOTIFY_SMTP_PASS
    from_addr = NOTIFY_FROM

    if NOTIFY_USE_EMAILRELAY == "on":
        relay_file = "/var/openfw/emailrelay/settings"
        if os.path.isfile(relay_file):
            with open(relay_file, "r") as f:
                for line in f:
                    if "=" in line:
                        k, v = line.strip().split("=", 1)
                        v = v.strip().strip(chr(39)).strip(chr(34))
                        if k in ("SMARTHOST_SERVER", "SMARTHOST", "SMTP_SERVER"):
                            server = v
                        if k in ("SMARTHOST_PORT", "SMTP_PORT"):
                            port = v
                        if k == "SMARTHOST_TLS":
                            if v == "on":
                                encryption = "tls"
            auth_file = "/etc/emailrelay.auth"
            if os.path.isfile(auth_file):
                with open(auth_file, "r") as f:
                    for line in f:
                        line = line.strip()
                        if line.startswith("#") or not line:
                            continue
                        import re
                        m = re.match(r"client\s+(?:plain|login|auth)\s+(\S+)\s+(.+)", line, re.IGNORECASE)
                        if m:
                            user = m.group(1)
                            passw = m.group(2)
                            auth = "on"
                            break
            if user == "" and os.path.isfile(relay_file):
                with open(relay_file, "r") as f:
                    for line in f:
                        if "=" in line:
                            k, v = line.strip().split("=", 1)
                            v = v.strip().strip(chr(39)).strip(chr(34))
                            if k in ("SMARTHOST_ACCOUNT", "SMTP_USER"):
                                user = v
                            if k in ("SMARTHOST_PASSWORD", "SMTP_PASS"):
                                passw = v
                if user != "":
                    auth = "on"
    elif NOTIFY_USE_EMAIL_BACKUP == "on":
        server = SMTP_SERVER
        port = SMTP_PORT if SMTP_PORT else "587"
        encryption = ENCRYPTION if ENCRYPTION else "tls"
        auth = SMTP_AUTH if SMTP_AUTH else "off"
        user = SMTP_USER
        passw = SMTP_PASS
        if user != "" and auth == "off":
            auth = "on"

    if from_addr == "":
        from_addr = "root@%s" % socket.gethostname().split(".")[0]

    return server, port, encryption, auth, user, passw, from_addr


def send_simple_email(server, port, encryption, auth, user, passw, from_addr, to_addr, subject, body):
    import smtplib
    import ssl
    try:
        port = int(port) if port else 25
        if encryption == "ssl":
            smtp = smtplib.SMTP_SSL(server, port, timeout=30)
        else:
            smtp = smtplib.SMTP(server, port, timeout=30)
            smtp.ehlo()
            if encryption == "tls":
                smtp.starttls()
                smtp.ehlo()
        if auth == "on" and user:
            smtp.login(user, passw)
        msg = "From: %s\r\nTo: %s\r\nSubject: %s\r\nMIME-Version: 1.0\r\nContent-Type: text/html; charset=UTF-8\r\n\r\n%s" % (from_addr, to_addr, subject, body)
        smtp.sendmail(from_addr, [to_addr], msg)
        smtp.quit()
        return True, "Notification sent successfully to %s" % to_addr
    except Exception as e:
        return False, "Failed to send notification: %s" % str(e)


def send_backup_notification(dest, success):
    global NOTIFY_ENABLED, NOTIFY_SUCCESS, NOTIFY_FAILURE, NOTIFY_TO, NOTIFY_SUBJECT_PREFIX
    if NOTIFY_ENABLED != "on" and NOTIFY_SUCCESS != "on" and NOTIFY_FAILURE != "on":
        return
    if success and NOTIFY_SUCCESS != "on":
        return
    if (not success) and NOTIFY_FAILURE != "on":
        return
    if not NOTIFY_TO:
        write_log("Notification skipped: no recipient configured.")
        return
    server, port, encryption, auth, user, passw, from_addr = get_notify_smtp_settings()
    if not server:
        write_log("Notification skipped: no SMTP server configured.")
        return
    status_text = "SUCCESS" if success else "FAILURE"
    prefix = NOTIFY_SUBJECT_PREFIX if NOTIFY_SUBJECT_PREFIX else "[OpenFW Backup]"
    status_word = "Success" if success else "Failure"
    subject = "Backup %s - %s" % (status_word, socket.gethostname())
    _host = socket.gethostname()
    _time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    _status_color = "#008100" if success else "#b00020"
    body = """<html>
<body style="margin:0;padding:0;background:#ffffff;font-family:Arial,Helvetica,sans-serif;color:#000000;">
  <table width="100%%" cellpadding="0" cellspacing="0" style="background:#008100;">
    <tr><td style="padding:16px;color:#ffffff;font-size:18px;font-weight:bold;">OpenFW Backup Notification</td></tr>
  </table>
  <table width="100%%" cellpadding="0" cellspacing="0" style="background:#ffffff;">
    <tr><td style="padding:20px;color:#000000;font-size:14px;">
      <p style="margin:0 0 12px 0;">Backup <b style="color:%s;">%s</b> on <b>%s</b></p>
      <table cellpadding="6" cellspacing="0" style="border:1px solid #008100;border-collapse:collapse;">
        <tr><td style="color:#008100;font-weight:bold;border:1px solid #008100;">Destination</td><td style="border:1px solid #008100;">%s</td></tr>
        <tr><td style="color:#008100;font-weight:bold;border:1px solid #008100;">Status</td><td style="border:1px solid #008100;color:%s;font-weight:bold;">%s</td></tr>
        <tr><td style="color:#008100;font-weight:bold;border:1px solid #008100;">Time</td><td style="border:1px solid #008100;">%s</td></tr>
        <tr><td style="color:#008100;font-weight:bold;border:1px solid #008100;">Host</td><td style="border:1px solid #008100;">%s</td></tr>
      </table>
    </td></tr>
  </table>
</body>
</html>""" % (_status_color, status_text, _host, dest, _status_color, status_text, _time, _host)
    ok, msg = send_simple_email(server, port, encryption, auth, user, passw, from_addr, NOTIFY_TO, subject, body)
    if ok:
        write_log("Notification sent: %s" % msg)
    else:
        write_log("Notification failed: %s" % msg)


def backup_attempted(dest):
    if dest == "MEGA":
        return MEGA_ENABLED == "on" and os.path.isfile(BASE_PATH + "/mega.conf")
    if dest == "FTP":
        return FTP_ENABLED == "on" and os.path.isfile(BASE_PATH + "/ftp.conf")
    if dest == "SFTP":
        return SFTP_ENABLED == "on" and os.path.isfile(BASE_PATH + "/sftp.conf")
    if dest == "SMB":
        return SMB_ENABLED == "on" and os.path.isfile(BASE_PATH + "/smb.conf")
    if dest == "GDRIVE":
        return GDRIVE_ENABLED == "on" and os.path.isfile(BASE_PATH + "/gdrive.conf")
    if dest == "EMAIL":
        return BACKUP_MAIL == "on"
    return False


def main():
    load_config()
    append_include_file()

    # Default to EmailRelay when it is installed/configured and the user has
    # not explicitly chosen otherwise (keeps the CGI default checkbox in sync).
    def _relay_has_smarthost():
        rf = "/var/openfw/emailrelay/settings"
        if not os.path.isfile(rf):
            return False
        try:
            with open(rf, "r") as f:
                for line in f:
                    if "=" in line:
                        k, v = line.strip().split("=", 1)
                        if k.strip() in ("SMARTHOST_SERVER", "SMARTHOST", "SMTP_SERVER"):
                            if v.strip().strip(chr(39)).strip(chr(34)) != "":
                                return True
        except Exception:
            pass
        return False

    if _relay_has_smarthost():
        # Only default when the key is absent from the conf file
        conf_text = ""
        if os.path.isfile(CONF_FILE):
            conf_text = open(CONF_FILE, "r").read()
        if "USE_EMAILRELAY=" not in conf_text:
            global USE_EMAILRELAY
            USE_EMAILRELAY = "on"
        if "NOTIFY_USE_EMAILRELAY=" not in conf_text:
            global NOTIFY_USE_EMAILRELAY
            NOTIFY_USE_EMAILRELAY = "on"

    arg = sys.argv[1] if len(sys.argv) > 1 else ""

    if arg == "--mega-cron":
        write_log("Starting scheduled MEGA backup task.")
        _res = do_mega_backup()
        if _res:
            write_log("MEGA backup completed successfully.")
        else:
            write_log("Error: MEGA backup task failed.")
        if backup_attempted("MEGA"):
            send_backup_notification("MEGA", bool(_res))
    elif arg == "--mega-sendnow":
        _res = do_mega_backup()
        if backup_attempted("MEGA"):
            send_backup_notification("MEGA", bool(_res))
    elif arg == "--ftp-cron":
        write_log("Starting scheduled FTP backup task.")
        _res = do_ftp_backup()
        if _res:
            write_log("FTP backup completed successfully.")
        else:
            write_log("Error: FTP backup task failed.")
        if backup_attempted("FTP"):
            send_backup_notification("FTP", bool(_res))
    elif arg == "--ftp-sendnow":
        _res = do_ftp_backup()
        if backup_attempted("FTP"):
            send_backup_notification("FTP", bool(_res))
    elif arg == "--sftp-cron":
        write_log("Starting scheduled SFTP backup task.")
        _res = do_sftp_backup()
        if _res:
            write_log("SFTP backup completed successfully.")
        else:
            write_log("Error: SFTP backup task failed.")
        if backup_attempted("SFTP"):
            send_backup_notification("SFTP", bool(_res))
    elif arg == "--sftp-sendnow":
        _res = do_sftp_backup()
        if backup_attempted("SFTP"):
            send_backup_notification("SFTP", bool(_res))
    elif arg == "--smb-cron":
        write_log("Starting scheduled SMB backup task.")
        _res = do_smb_backup()
        if _res:
            write_log("SMB backup completed successfully.")
        else:
            write_log("Error: SMB backup task failed.")
        if backup_attempted("SMB"):
            send_backup_notification("SMB", bool(_res))
    elif arg == "--smb-sendnow":
        _res = do_smb_backup()
        if backup_attempted("SMB"):
            send_backup_notification("SMB", bool(_res))
    elif arg == "--gdrive-cron":
        write_log("Starting scheduled Google Drive backup task.")
        _res = do_gdrive_backup()
        if _res:
            write_log("Google Drive backup completed successfully.")
        else:
            write_log("Error: Google Drive backup task failed.")
        if backup_attempted("GDRIVE"):
            send_backup_notification("GDRIVE", bool(_res))
    elif arg == "--gdrive-sendnow":
        _res = do_gdrive_backup()
        if backup_attempted("GDRIVE"):
            send_backup_notification("GDRIVE", bool(_res))
    elif arg == "--email-cron":
        write_log("Starting scheduled EMAIL backup task.")
        _res = do_email_backup()
        if _res:
            write_log("EMAIL backup completed successfully.")
        else:
            write_log("Error: EMAIL backup task failed.")
        if backup_attempted("EMAIL"):
            send_backup_notification("EMAIL", bool(_res))
    elif arg == "--email-sendnow":
        _res = do_email_backup()
        if backup_attempted("EMAIL"):
            send_backup_notification("EMAIL", bool(_res))
    else:
        generate_mega_conf()
        generate_ftp_conf()
        generate_sftp_conf()
        generate_smb_conf()
        generate_gdrive_conf()
        update_cron()


if __name__ == "__main__":
    main()