#!/bin/bash
set -e

# Set up directory structure
WORKDIR="$HOME/dev/hurd/upstream"
GNU_PREFIX="$HOME/gnu"
MIG_REPO="https://git.savannah.gnu.org/git/hurd/mig.git"
MACH_REPO="https://git.savannah.gnu.org/git/hurd/gnumach.git"
HURD_REPO="git://git.savannah.gnu.org/hurd/hurd.git"

echo "==> Updating APT and installing base development tools..."
sudo apt update
sudo apt install -y vim git build-essential autoconf automake m4 bison flex texinfo xorriso libparted-dev pkg-config ncurses-term rsync ripgrep pip pipx

mkdir -p "$WORKDIR"
cd "$WORKDIR"

echo "==> Cloning MiG, GNU Mach, and Hurd..."
[ ! -d "mig" ] && git clone "$MIG_REPO"
[ ! -d "gnumach" ] && git clone "$MACH_REPO"
[ ! -d "hurd" ] && git clone "$HURD_REPO"

echo "==> Building and installing MiG..."
cd "$WORKDIR/mig"
autoreconf --install
rm -rf build && mkdir build && cd build
mkdir -p "$GNU_PREFIX"
TARGET_CPPFLAGS="-I$GNU_PREFIX/include" ../configure --prefix="$GNU_PREFIX"
make -j$(nproc)
make install

# Persist PATH update
if ! grep -q "$GNU_PREFIX/bin" ~/.bashrc; then
    echo "export PATH=\"$GNU_PREFIX/bin:\$PATH\"" >> ~/.bashrc
fi
export PATH="$GNU_PREFIX/bin:$PATH"

echo "==> Building GNU Mach..."
cd "$WORKDIR/gnumach"
autoreconf --install
rm -rf build && mkdir build && cd build
../configure --prefix=
make gnumach.gz

echo "==> Building Hurd..."
cd "$WORKDIR/hurd"
autoreconf -fi
rm -rf build && mkdir build && cd build
../configure 
make -j$(nproc)

echo -e "\n All done. If this is your first run, do:"
echo "source ~/.bashrc"
