#!/bin/sh
# script/bootstrap: install all dependencies needed to build and develop
# this repo. Idempotent: every install is guarded by a check so already
# installed tools are skipped. Installs base tooling with nix, apt, or
# brew (detected in that order); assumes nothing is present.
set -eu

ROOT="$(cd "$(dirname "$0")/.." && pwd -P)"

PKGMGR=""
SUDO=""

detect_pkgmgr() {
    if command -v nix-env >/dev/null 2>&1; then
        PKGMGR="nix"
    elif command -v apt-get >/dev/null 2>&1; then
        PKGMGR="apt"
    elif command -v brew >/dev/null 2>&1; then
        PKGMGR="brew"
    else
        echo "bootstrap: no supported package manager (nix, apt, brew)" >&2
        exit 1
    fi
    if [ "$PKGMGR" = "apt" ]; then
        export DEBIAN_FRONTEND=noninteractive
        if [ "$(id -u)" != "0" ]; then
            SUDO="sudo"
        fi
    fi
}

# pkg_install <nix-attr> <apt-pkg> <brew-formula>
pkg_install() {
    case "$PKGMGR" in
        nix) nix-env -iA "nixpkgs.$1" ;;
        apt) $SUDO env DEBIAN_FRONTEND=noninteractive apt-get install -y "$2" ;;
        brew) brew install "$3" ;;
    esac
}

missing() {
    ! command -v "$1" >/dev/null 2>&1
}

main() {
    cd "$ROOT"
    detect_pkgmgr

    if missing git; then pkg_install git git git; fi
    if missing make; then pkg_install gnumake make make; fi
    if missing node; then pkg_install nodejs nodejs node; fi
    if missing yarn; then
        # corepack ships with node >= 16 and provides yarn
        if command -v corepack >/dev/null 2>&1; then
            corepack enable
        else
            pkg_install yarn yarnpkg yarn
        fi
    fi

    yarn install --frozen-lockfile
    echo "bootstrap complete"
}

main "$@"
