website-staging-server/index.ts

88 lines
1.9 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");
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;
}
updateWebsite("main");
res.send("Updated!");
});
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) => {
console.log(cwd ? `${cwd} >` : ">", cmd);
const out = execSync(cmd, { cwd, encoding: "utf8" });
console.log(out);
return out;
};
// Makes sure that the directory is present
$(`mkdir -p ${WWW_DIR}`);
function updateWebsite(branch: string) {
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_$(`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!");
}