1#!/usr/bin/env python3
2"""Prepare owned Git repositories and preserve Shale account bindings."""
3import json
4import os
5from pathlib import Path
6import re
7import sqlite3
8import sys
9
10data = json.load(sys.stdin)
11root = Path(data["hostRoot"])
12for config in (root / "repositories_owned").glob("*/config"):
13 text = config.read_text()
14 if not re.search(r"(?im)^\s*receivepack\s*=", text):
15 # Shale authorizes pushes before CGI; its own repository initializer enables this.
16 with config.open("a") as file:
17 file.write("\n[http]\n\treceivepack = true\n")
18path = root / "data/astheno.shale.db"
19if path.exists():
20 domain = os.environ["STUDIO_DOMAIN"]
21 old, new = "auth." + domain + "/realms/master", "snowglobe." + domain
22 db = sqlite3.connect(path, timeout=30)
23 db.execute("BEGIN IMMEDIATE")
24 if db.execute("SELECT 1 FROM users old JOIN users new ON old.snowflake=new.snowflake WHERE old.provider=? AND new.provider=?", (old,new)).fetchone():
25 raise ValueError("duplicate Shale identity; resolve it before moving the issuer")
26 count = db.execute("UPDATE users SET provider=? WHERE provider=?", (new,old)).rowcount
27 db.commit()
28 assert db.execute("PRAGMA quick_check").fetchone() == ("ok",)
29 db.close()
30 print("Moved", count, "existing Shale identity bindings to Snowglobe")