#!/command/with-contenv bash

set -eu
cd /app/bgutil-ytdlp-pot-provider/server
chmod -c 00755 ../node

tmp_app_home="$(realpath -e "$(mktemp --directory --tmpdir=.)")"
trap "rm -rf ${tmp_app_home}" EXIT

command -v deno >/dev/null || \
    /app/install_deno.sh

test '!' -d build || \
    test '!' -f build/main.js || \
    test '!' -d node_modules || \
    exit 0 # nothing needs to be built

command -v node > /dev/null || \
    install -v -t /usr/local/bin ../node

chown -R app:app .

s6-setuidgid app \
    env HOME="${tmp_app_home}" DENO_COMPAT=1 deno run --no-config -A npm:npm ci --no-fund

s6-setuidgid app \
    env HOME="${tmp_app_home}" DENO_COMPAT=1 deno run --no-config -A npm:npm audit fix

s6-setuidgid app \
    env HOME="${tmp_app_home}" ../node npm:typescript/tsc

chown -R root:app .
