import { execFileSync } from "node:child_process"; const required = ["GITEA_URL", "GITEA_OWNER", "GITEA_TOKEN"]; const missing = required.filter((name) => !process.env[name]); if (missing.length) { console.error( `Missing required environment variables: ${missing.join(", ")}`, ); process.exit(2); } const base = process.env.GITEA_URL.replace(/\/$/, ""); const owner = process.env.GITEA_OWNER; const token = process.env.GITEA_TOKEN; const name = "DockDeck"; const headers = { Authorization: `token ${token}`, "content-type": "application/json", }; let response = await fetch( `${base}/api/v1/repos/${encodeURIComponent(owner)}/${encodeURIComponent(name)}`, { headers }, ); if (response.status === 404) { response = await fetch(`${base}/api/v1/user/repos`, { method: "POST", headers, body: JSON.stringify({ name, private: true, auto_init: false, description: "A premium personal launchpad for Unraid services.", }), }); } if (!response.ok) { console.error( `Gitea repository initialization failed with HTTP ${response.status}.`, ); process.exit(1); } const repository = await response.json(); if (!repository.private || repository.owner?.login !== owner) { console.error( "Gitea returned a repository with an unexpected owner or visibility. Aborting.", ); process.exit(1); } const remoteUrl = `${base}/${encodeURIComponent(owner)}/${name}.git`; let currentRemote = ""; try { currentRemote = execFileSync("git", ["remote", "get-url", "origin"], { encoding: "utf8", }).trim(); } catch { /* no origin yet */ } if (currentRemote && currentRemote !== remoteUrl) { console.error( "An origin remote already exists with a different URL. No changes were made.", ); process.exit(1); } if (!currentRemote) execFileSync("git", ["remote", "add", "origin", remoteUrl], { stdio: "inherit", }); execFileSync( "git", [ "-c", `http.extraHeader=Authorization: token ${token}`, "push", "-u", "origin", "main", ], { stdio: ["ignore", "inherit", "inherit"], }, ); console.log(`Private repository ready at ${base}/${owner}/${name}`);