#!/bin/sh

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

set -e

ROOT=test_environment
FRESH=clean_environment

TARBALL=archlinux-bootstrap-x86_64.tar.zst
REPO="https://geo.mirror.pkgbuild.com"

if test -e "$FRESH"
then
    echo "Clean arch environment found at $FRESH. Good."
else
    echo "No arch environment found at $FRESH, downloading from $REPO"
    curl -O "$REPO/iso/latest/$TARBALL"
    tar -xf "$TARBALL"
    mv root.x86_64 "$FRESH"
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."

./cleanup add_mounts

chmod 1777 "$ROOT/tmp"

echo 'Server = http://ftp.swin.edu.au/archlinux/$repo/os/$arch' > "$ROOT/etc/pacman.d/mirrorlist"
cp /etc/resolv.conf "$ROOT/etc/resolv.conf"


cp -r install_scripts "$ROOT/root"

chroot "$ROOT" /root/install_scripts/user_setup "$@" || echo Script failed.

./cleanup mounts
