#!/bin/sh

if test `id -u` -ne 0
then
    echo "$0 must be run as root."
    return
fi

ROOT=test_environment
FRESH=clean_environment

TARBALL=xbps-static-static-0.59_5.x86_64-musl.tar.xz
# See https://xmirror.voidlinux.org/ for other mirrors.
REPO=https://ftp.swin.edu.au/voidlinux

if test -e "$FRESH"
then
    echo "Void installation found at $FRESH. Good."
else
    if test -e "$TARBALL"
    then
        echo "Tarball found."
    else
        URL="$REPO/static/$TARBALL"
        echo "Fetching tarball from $URL"
        curl "$URL" -O
    fi

    mkdir "$FRESH"
    tar xf "$TARBALL" -C "$FRESH"

    mkdir -p "$FRESH/etc/xbps.d"
    echo "repository=$REPO/current" > "$FRESH/etc/xbps.d/00-repository-main.conf"

    XBPS_ARCH=x86_64 "$FRESH/usr/bin/xbps-install.static" -r "$FRESH" -S base-system
fi

if test -e "$ROOT"
then
    echo "Existing installation found at $ROOT, removing."
    ./cleanup
fi

echo "Copying $FRESH to $ROOT."
cp -r "$FRESH" "$ROOT"

echo "Initializing $ROOT."

chmod 1777 "$ROOT"
chmod 1777 "$ROOT/bin"
chmod 1777 "$ROOT/tmp"
chmod 4755 "$ROOT/usr/bin/sudo"

# Add DNS configs
cp /etc/resolv.conf "$ROOT/etc/resolv.conf"

cp -r install_scripts "$ROOT/root"

./cleanup add_mounts

chroot "$ROOT" /root/install_scripts/user_setup "$@"

./cleanup mounts
