website-staging-server/index.ts

88 lines
1.9 KiB
TypeScript
Raw Normal View History

2021-05-27 20:32:12 -04:00
import { execSync } from "child_process";
2021-07-20 05:54:41 -04:00
import path from "path";
import dotenv from "dotenv";
2021-07-20 05:54:41 -04:00
import Express from "express";
2021-05-27 20:32:12 -04:00
dotenv.config();
2021-05-27 20:32:12 -04:00
const app = Express();
2021-05-27 21:29:21 -04:00
const PORT = process.env.PORT;
2021-05-27 20:32:12 -04:00
2021-06-07 21:28:49 -04:00
const base64 = Buffer.from(
2021-07-20 05:54:41 -04:00
`${process.env.GITEA_USER}:${process.env.PASS}`,
2021-06-07 21:28:49 -04:00
).toString("base64");
2021-05-27 20:32:12 -04:00
2021-06-14 19:08:42 -04:00
app.post("/", (req, res) => {
2021-05-27 20:32:12 -04:00
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;
}
2021-07-20 05:54:41 -04:00
updateWebsite("main");
2021-06-14 19:08:42 -04:00
2021-07-20 05:54:41 -04:00
res.send("Updated!");
2021-05-27 20:32:12 -04:00
});
app.listen(PORT, () => {
console.log(`👀 http://localhost:${PORT}`);
2021-05-27 20:32:12 -04:00
});
2021-07-20 05:54:41 -04:00
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);
2021-05-27 20:32:12 -04:00
2021-07-20 05:54:41 -04:00
const out = execSync(cmd, { cwd, encoding: "utf8" });
console.log(out);
2021-05-27 20:32:12 -04:00
2021-07-20 05:54:41 -04:00
return out;
};
2021-06-14 19:08:42 -04:00
2021-07-20 05:54:41 -04:00
// 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}`);
2021-07-20 05:54:41 -04:00
$(`rm -rf ${tmpDir}`);
2021-07-20 06:15:00 -04:00
console.log("Done!");
}