From 7307ee9f4d0d444addbf09107b46bfb3c2e00165 Mon Sep 17 00:00:00 2001
From: Davide Gardenal <davide.gardenal@huawei.com>
Date: Tue, 26 Jul 2022 17:42:01 +0200
Subject: [PATCH] upgrade_oniro: implement backup_oniro

Implment backup_oniro, now the script can backup the project so
that in case something goes wrong in the upgrade we can restore
the initial state (this function is not yer implement).
Add TODOs.

Signed-off-by: Davide Gardenal <davide.gardenal@huawei.com>
---
 scripts/upgrade_oniro/upgrade_oniro.py | 27 ++++++++++++++++++++++++--
 1 file changed, 25 insertions(+), 2 deletions(-)

diff --git a/scripts/upgrade_oniro/upgrade_oniro.py b/scripts/upgrade_oniro/upgrade_oniro.py
index de1200ec..ac7604dd 100644
--- a/scripts/upgrade_oniro/upgrade_oniro.py
+++ b/scripts/upgrade_oniro/upgrade_oniro.py
@@ -39,7 +39,8 @@
 # 7. In case of a successful upgrade print/dump some additional information about the upgrade (CVE diff, buildhistory, ...)
 #
 # TODO think about a way to let the user know BEFORE the upgrade what changed so (s)he can choose. (maybe you can use git diff --compact-summary)
-
+# TODO check if the script is executed in the top level directory of the project
+# TODO check that if build_directory exists then it must be a directory
 
 import argparse
 import pathlib
@@ -94,7 +95,29 @@ def perform_pre_upgrade_checks():
     return
 
 def backup_oniro():
-    # TODO
+    # This will back up:
+    #   - All layers specified in the Oniro Manifest
+    #   - .repo folder
+    #   - If build_directory is not empty, backup its content excluding tmp* and tmp-newlib* directories
+    # TODO add function description
+    # TODO add more verbose log
+    from upgrade_oniro_utils import get_manifest_projects
+    from datetime import datetime
+    import tarfile
+
+    backup_folders = [layer["path"] for layer in get_manifest_projects()] # add all manifest layers
+    backup_folders.append(".repo")
+    if build_directory.exists():
+        for child in  build_directory.iterdir():
+            if child.is_dir() and "tmp" not in child.name and child.name != "downloads":
+                backup_folders.append(f"{build_directory.name}/{child.name}")
+    
+    archive_name = f"upgrade_oniro_backup-{datetime.timestamp(datetime.now())}.tar.gz"
+    with tarfile.open(archive_name, "w:gz") as tar_archive:
+        for folder in backup_folders:
+            tar_archive.add(folder)
+            print(f"{folder} has been backed up")
+    
     return
 
 def restore_oniro():
-- 
GitLab