Add option to clear the DB when deploying the scouting app

Signed-off-by: Philipp Schrader <philipp.schrader@gmail.com>
Change-Id: I24e1687732eac36561cb8f1cfb4fb1a517895704
diff --git a/scouting/deploy/deploy.py b/scouting/deploy/deploy.py
index 5967956..2f14f07 100644
--- a/scouting/deploy/deploy.py
+++ b/scouting/deploy/deploy.py
@@ -19,9 +19,38 @@
         default="scouting.frc971.org",
         help="The SSH host to install the scouting web server to.",
     )
+    parser.add_argument(
+        "--clear-db",
+        action="store_true",
+        help=("If set, will stop the existing scouting server and clear the "
+              "database before deploying the new one."),
+    )
     args = parser.parse_args(argv[1:])
     deb = Path(args.deb)
 
+    if args.clear_db:
+        print("Stopping the scouting app.")
+        subprocess.run(
+            f"ssh -tt {args.host} sudo systemctl stop scouting.service",
+            # In case the scouting app isn't installed, ignore the error here.
+            check=False,
+            stdin=sys.stdin)
+        print("Clearing the database.")
+        subprocess.run(
+            " ".join([
+                f"ssh -tt {args.host} sudo -u postgres psql",
+                # Drop all tables in the same schema.
+                "-c 'drop schema public cascade;'",
+                # Create an empty schema for the scouting app to use.
+                "-c 'create schema public;'",
+                # List all tables as a sanity check.
+                "-c '\dt'",
+                "postgres",
+            ]),
+            shell=True,
+            check=True,
+            stdin=sys.stdin)
+
     # Copy the .deb to the scouting server, install it, and delete it again.
     subprocess.run(["rsync", "-L", args.deb, f"{args.host}:/tmp/{deb.name}"],
                    check=True,