#!/bin/sh

PKG="$1"
PORTS_DIR="/usr/ports/tmp"
URL="https://dists.jewguard.xyz/bigratos/${PKG}.tar.gz"
TMPFILE="${PORTS_DIR}/${PKG}.tar.gz"
WORKDIR="${PORTS_DIR}/${PKG}"
fail() {
    echo "error: $1"
    exit 1
}

check_dep() {
    [ -x "$1" ] || fail "$2"
}

echo ">> RAT-CONFTEST stage started"

ARCH="$(uname -m)"
GCC_VER="$(gcc -dumpfullversion 2>/dev/null)"

echo "[1/4] GCC-VERS: ${GCC_VER:-UNKNOWN}"
echo "[2/4] ARCHITECTURE: $ARCH"

check_dep /bin/sh "SH (core script dependency) is not executable"
echo "[3/4] IS-SH-AVAILABLE: YES"

check_dep /bin/curl "CURL (core script dependency) is not executable"
echo "[4/4] IS-CURL-AVAILABLE: YES"

echo ">> RAT-CONFTEST stage completed"

mkdir -p "$PORTS_DIR" || fail "failed to create ports directory"

echo ">> fetching $PKG ..."
curl -fL "$URL" -o "$TMPFILE" || fail "failed to fetch $PKG"

echo ">> extracting"
mkdir -p "$WORKDIR" || fail "failed to create work directory"

tar -xvzf "$TMPFILE" \
    --strip-components=1 \
    -C "$WORKDIR" || fail "failed to extract archive"

echo ">> compiling / installing"

cd "$WORKDIR" || fail "failed to enter work directory"
sh -e build.sh || fail "build/install failed"

echo ">> done."

rm -f "$TMPFILE"
