From f139af4f528d2835be3b36a3b7c9da7fc8f683ba Mon Sep 17 00:00:00 2001
From: Joe Kaufeld <opensource@joekaufeld.com>
Date: Sat, 23 Jul 2022 14:48:28 -0400
Subject: [PATCH] add update system

---
 src/cli.py             | 15 +++++++++++++--
 src/commands/update.py | 22 +++++++++++++---------
 2 files changed, 26 insertions(+), 11 deletions(-)

diff --git a/src/cli.py b/src/cli.py
index 22ec457..9e1a69e 100644
--- a/src/cli.py
+++ b/src/cli.py
@@ -3,6 +3,8 @@ import argparse
 import importlib
 import sys
 
+import src
+
 BANNER = """
                 .    o8o  oooo   o8o      .    o8o                     
               .o8    `"'  `888   `"'    .o8    `"'                     
@@ -17,11 +19,20 @@ def main():
     parser = argparse.ArgumentParser(
         description='Run a specific script by name. If no name is provided, start a REPL.'
     )
-    parser.add_argument('user_input', type=str, nargs='*',
-                        help='The name of the script that you want to run plus any arguments for that script.')
+    parser.add_argument(
+        'user_input',
+        type=str,
+        nargs='*',
+        help='The name of the script that you want to run plus any arguments for that script.')
+    parser.add_argument(
+        '--version', action='store_true', help="Print out the version string."
+    )
 
     args = parser.parse_args()
     user_input = args.user_input
+    if args.version is True:
+        print(src.__version__)
+        sys.exit()
     if len(user_input) == 0:
         code.interact(banner=BANNER, local=locals())
     else:
diff --git a/src/commands/update.py b/src/commands/update.py
index e776dc4..052ad1d 100644
--- a/src/commands/update.py
+++ b/src/commands/update.py
@@ -1,15 +1,9 @@
 import httpx
-import json
-import sys
-import zipfile
-from datetime import datetime
+
+import src
 
 
 def main(args):
-    self_name = sys.argv[0].strip(".").strip("/")  # todo: is this resilient?
-    data = json.loads(zipfile.ZipFile(self_name).read("environment.json"))
-    build_time = datetime.fromisoformat(data['built_at'])
-
     release_data = httpx.get(
         'https://api.github.com/repos/itsthejoker/utils/releases/latest'
     )
@@ -19,4 +13,14 @@ def main(args):
             f" {release_data.status_code} with the following content:\n"
             f"{release_data.content}"
         )
-        sys.exit()
+        return
+    json_data = release_data.json()
+    if json_data['name'] == src.__version__:
+        print("Server version is the same as current version; nothing to update.")
+        return
+
+    url = json_data['assets'][0]['browser_download_url']
+    with open('utils', 'wb') as f, httpx.stream("GET", url, follow_redirects=True) as r:
+        for line in r.iter_bytes():
+            f.write(line)
+    print(f"Updated to {json_data['name']}! 🎉")