From cf9ad778799a7756f57e25b3d0612036ce087d50 Mon Sep 17 00:00:00 2001
From: Andrew <mcdeweykp@gmail.com>
Date: Fri, 20 Jan 2023 17:35:30 -0500
Subject: [PATCH] Add option to run command before backup

---
 .../controllers/management_controller.py      |  9 ++++++-
 app/classes/models/management.py              |  6 +++++
 app/classes/shared/server.py                  |  8 ++++++
 app/classes/web/panel_handler.py              |  2 ++
 .../templates/panel/server_backup.html        | 27 +++++++++++++++++++
 app/migrations/20230120_backup_command.py     | 16 +++++++++++
 6 files changed, 67 insertions(+), 1 deletion(-)
 create mode 100644 app/migrations/20230120_backup_command.py

diff --git a/app/classes/controllers/management_controller.py b/app/classes/controllers/management_controller.py
index 47860fe1..8f46adc2 100644
--- a/app/classes/controllers/management_controller.py
+++ b/app/classes/controllers/management_controller.py
@@ -145,9 +145,16 @@ class ManagementController:
         excluded_dirs: list = None,
         compress: bool = False,
         shutdown: bool = False,
+        command: str = "",
     ):
         return self.management_helper.set_backup_config(
-            server_id, backup_path, max_backups, excluded_dirs, compress, shutdown
+            server_id,
+            backup_path,
+            max_backups,
+            excluded_dirs,
+            compress,
+            shutdown,
+            command,
         )
 
     @staticmethod
diff --git a/app/classes/models/management.py b/app/classes/models/management.py
index 55c86bb7..10529898 100644
--- a/app/classes/models/management.py
+++ b/app/classes/models/management.py
@@ -131,6 +131,7 @@ class Backups(BaseModel):
     server_id = ForeignKeyField(Servers, backref="backups_server")
     compress = BooleanField(default=False)
     shutdown = BooleanField(default=False)
+    command = CharField(default="")
 
     class Meta:
         table_name = "backups"
@@ -369,6 +370,7 @@ class HelpersManagement:
                 "server_id": row.server_id_id,
                 "compress": row.compress,
                 "shutdown": row.shutdown,
+                "command": row.command,
             }
         except IndexError:
             conf = {
@@ -378,6 +380,7 @@ class HelpersManagement:
                 "server_id": server_id,
                 "compress": False,
                 "shutdown": False,
+                "command": "",
             }
         return conf
 
@@ -393,6 +396,7 @@ class HelpersManagement:
         excluded_dirs: list = None,
         compress: bool = False,
         shutdown: bool = False,
+        command: str = "",
     ):
         logger.debug(f"Updating server {server_id} backup config with {locals()}")
         if Backups.select().where(Backups.server_id == server_id).exists():
@@ -405,6 +409,7 @@ class HelpersManagement:
                 "server_id": server_id,
                 "compress": False,
                 "shutdown": False,
+                "command": "",
             }
             new_row = True
         if max_backups is not None:
@@ -414,6 +419,7 @@ class HelpersManagement:
             conf["excluded_dirs"] = dirs_to_exclude
         conf["compress"] = compress
         conf["shutdown"] = shutdown
+        conf["command"] = command
         if not new_row:
             with self.database.atomic():
                 if backup_path is not None:
diff --git a/app/classes/shared/server.py b/app/classes/shared/server.py
index 745d840d..43bdc72d 100644
--- a/app/classes/shared/server.py
+++ b/app/classes/shared/server.py
@@ -1024,6 +1024,14 @@ class ServerInstance:
             )
         time.sleep(3)
         conf = HelpersManagement.get_backup_config(self.server_id)
+        if conf["command"]:
+            if self.check_running():
+                logger.debug(
+                    "Found running server and send command option. Sending command"
+                )
+                self.send_command(conf["command"])
+            # pause to let people read message.
+            time.sleep(5)
         if conf["shutdown"]:
             logger.info(
                 "Found shutdown preference. Delaying"
diff --git a/app/classes/web/panel_handler.py b/app/classes/web/panel_handler.py
index 582517db..8a439a86 100644
--- a/app/classes/web/panel_handler.py
+++ b/app/classes/web/panel_handler.py
@@ -1678,6 +1678,7 @@ class PanelHandler(BaseHandler):
             compress = self.get_argument("compress", False)
             shutdown = self.get_argument("shutdown", False)
             check_changed = self.get_argument("changed")
+            command = self.get_argument("backup_command", "")
             if str(check_changed) == str(1):
                 checked = self.get_body_arguments("root_path")
             else:
@@ -1701,6 +1702,7 @@ class PanelHandler(BaseHandler):
                 excluded_dirs=checked,
                 compress=bool(compress),
                 shutdown=bool(shutdown),
+                command=command,
             )
 
             self.controller.management.add_to_audit_log(
diff --git a/app/frontend/templates/panel/server_backup.html b/app/frontend/templates/panel/server_backup.html
index a50b55b5..d509d359 100644
--- a/app/frontend/templates/panel/server_backup.html
+++ b/app/frontend/templates/panel/server_backup.html
@@ -107,6 +107,23 @@
                   translate('serverBackups', 'shutdown', data['lang']) }}
                   {% end %}
                 </div>
+                <div class="form-group">
+                  <label for="command-check" class="form-check-label ml-4 mb-4"></label>
+                  {% if data['backup_config']['command'] %}
+                  <input type="checkbox" class="form-check-input" id="command-check" name="command-check" checked>Run
+                  Command Before Backup
+                  <br>
+                  <input type="text" class="form-control" name="backup_command" id="backup_command"
+                    value="{{ data['backup_config']['command'] }}" placeholder="We enter the / for you"
+                    style="display: inline-block;">
+                  {% else %}
+                  <input type="checkbox" class="form-check-input" id="command-check" name="command-check">Run Command
+                  Before Backup
+                  <br>
+                  <input type="text" class="form-control" name="backup_command" id="backup_command" value=""
+                    placeholder="We enter the / for you." style="display: none;">
+                  {% end %}
+                </div>
                 <div class="form-group">
                   <label for="server">{{ translate('serverBackups', 'exclusionsTitle', data['lang']) }} <small> - {{
                       translate('serverBackups', 'excludedChoose', data['lang']) }}</small></label>
@@ -344,6 +361,16 @@
     });
   }
 
+  $("#command-check").on("click", function () {
+    console.log("in command-check")
+    if ($("#command-check:checked").val()) {
+      $("#backup_command").css("display", "inline-block");
+      console.log("in if")
+    } else {
+      $("#backup_command").css("display", "none");
+      $("#backup_command").val("");
+    }
+  });
 
   $(document).ready(function () {
     try {
diff --git a/app/migrations/20230120_backup_command.py b/app/migrations/20230120_backup_command.py
new file mode 100644
index 00000000..21402647
--- /dev/null
+++ b/app/migrations/20230120_backup_command.py
@@ -0,0 +1,16 @@
+# Generated by database migrator
+import peewee
+
+
+def migrate(migrator, database, **kwargs):
+    migrator.add_columns("backups", command=peewee.CharField(default=""))
+    """
+    Write your migrations here.
+    """
+
+
+def rollback(migrator, database, **kwargs):
+    migrator.drop_columns("backups", ["command"])
+    """
+    Write your rollback migrations here.
+    """