#!/bin/sh -e
#
# Create/destroy temporary chroots.

log() {
    printf '\033[31;1m->\033[m %s.\n' "$@"
}

clean() {
    log "Destroying chroot"
    su -c "rm -rf chroot-$pid" || clean
}

pid=$$

cd "${cac_dir:=$KISS_ROOT${XDG_CACHE_HOME:-$HOME/.cache}/kiss}"

[ -f carbs-rootfs.tar.xz ] || {
    log "Downloading chroot tarball"
    wget https://dl.carbslinux.org/releases/carbs-rootfs.tar.xz
}

[ -d carbs-chroot ] || {
    log "Extracting chroot"
    mkdir -p carbs-chroot
    tar xvf carbs-rootfs.tar.xz -C carbs-chroot
}

log "Creating temporary chroot"
cp -a carbs-chroot "chroot-$pid"

trap clean EXIT INT

log "Entering chroot"
su -c "kiss-chroot chroot-$pid"