website-staging-server/index.ts

111 lines
2.3 KiB
TypeScript

import { execSync } from "child_process";
import path from "path";
import dotenv from "dotenv";
import Express from "express";
dotenv.config();
const app = Express();
const PORT = process.env.PORT;
const base64 = Buffer.from(
`${process.env.GITEA_USER}:${process.env.PASS}`,
).toString("base64");
app.post("/", (req, res) => {
const header = req.header("authorization");
const branch = req.header("x-branch");
if (header == null) {
res.status(403).send("Authorization header is needed");
return;
}
if (header.split(" ").length !== 2) {
res.status(400).send("Authorization header is malformed");
return;
}
const [type, secret] = header.split(" ");
if (type !== "Basic") {
res.status(400).send("Only basic authorization is supported");
return;
}
if (secret !== base64) {
res.status(401).send("Incorrect username or password");
return;
}
res.send(updateWebsite(branch ?? "main"));
});
app.listen(PORT, () => {
console.log(`👀 http://localhost:${PORT}`);
});
const USER = process.env.USER!;
const REPO_NAME = "www-new";
const URL = `https://git.csclub.uwaterloo.ca/www/${REPO_NAME}.git`;
const WWW_DIR = process.env.WWW_DIR ?? "~/www/csc";
const $ = (
cmd: string,
cwd?: string,
log: (..._: string[]) => void = console.log,
) => {
log(cwd ? `${cwd} >` : ">", cmd);
const out = execSync(cmd, { cwd, encoding: "utf8" });
log(out);
return out;
};
function createLogger$() {
const logs: string[] = [];
const log = (...args: string[]) => {
console.log(...args);
logs.push(args.join(" "));
};
return {
$: (cmd: string, cwd?: string) => $(cmd, cwd, log),
logs,
};
}
// Makes sure that the directory is present
$(`mkdir -p ${WWW_DIR}`);
function updateWebsite(branch: string) {
const { $, logs } = createLogger$();
const tmpDir = $("mktemp --directory").trim();
$(`git clone ${URL}`, tmpDir);
const repo_$ = (cmd: string) => $(cmd, path.join(tmpDir, REPO_NAME));
repo_$(`git checkout ${branch}`);
repo_$(`npm install`);
repo_$(
`USE_LDAP=true NEXT_PUBLIC_BASE_PATH="/~${USER}/csc/${branch}" npm run build`,
);
repo_$(`npm run export`);
const finalDir = path.join(WWW_DIR, branch);
$(`rm -rf ${finalDir}`);
$(`mkdir -p ${finalDir}`);
repo_$(`mv ./out/* ${finalDir}`);
$(`rm -rf ${tmpDir}`);
console.log("Done!");
return logs.join("\n");
}