#!/bin/zsh
DIR=$0:a:h
PS4='+%B%* %F{cyan}%N%f:%F{yellow}%i%f>%b '

cd "$DIR"

declare -A NEW_ENV
NEW_ENV[HOST]=$DIR:t
NEW_ENV[HOME]=/root/
NEW_ENV[PATH]="/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/sbin:/usr/local/bin"
NEW_ENV[TERM]=$TERM
# NEW_ENV[TERM]="${TERM%-256color}"
(($+MAKEOPTS)) && NEW_ENV[MAKEOPTS]=$MAKEOPTS
(($+FEATURES)) && NEW_ENV[FEATURES]=$FEATURES
(($+EMERGE_DEFAULT_OPTS)) && NEW_ENV[EMERGE_DEFAULT_OPTS]=$EMERGE_DEFAULT_OPTS

do_chroot() {
        local -a call

        # reset environment
        call=( env -i - )
        for key val in ${(kv)NEW_ENV}; do
                call+="$key=$val"
        done

        # linux32 or equivalent
        (($+SETARCH)) && call+=( setarch $SETARCH )

        # the actual chroot call
        call+=( chroot . )

        if (($+EATMYDATA)); then
                if [[ -x usr/bin/eatmydata ]]; then
                        call+=( /usr/bin/eatmydata )
                else
                        echo >&2 '/usr/bin/eatmydata not present!'
                fi
        fi

        # do it!
        "${call[@]}" "$@"

        RET=$?
        echo "command $* returned $RET"
}

umount=( )

trymount() {
        local DST=${*[-1]}
        if mount | grep -q "$DIR/$DST"
        then
                echo "$DST already mounted"
        else
                echo "mounting $DST"
                mount "$@"
                umount=( $DST $umount )
        fi
}

[[ -f ./chroot.conf ]] && source ./chroot.conf

: ${PORTDIR:=/usr/portage}
: ${DISTDIR:=/var/portage/distfiles}
: ${TMPFS_SIZE:=100M}

mkdir -v -p dev/{pts,shm}
trymount -t devpts -o gid=5 devpts dev/pts
trymount -t tmpfs -o size=$TMPFS_SIZE  tmpfs dev/shm

trymount -t proc none proc

[[ -d usr/portage ]] && \
        trymount --bind $PORTDIR usr/portage/gentoo
[[ -d var/portage/distfiles ]] && \
        trymount --bind $DISTDIR var/portage/distfiles

cp -v /etc/resolv.conf etc/

if [[ -f etc/mtab ]]; then
        rm etc/mtab
        ln -s /proc/mounts etc/mtab
fi

if (($#)); then
        do_chroot "$@"
elif [[ -f ./bin/login ]]; then
        do_chroot /bin/login -f root
else
        do_chroot $SHELL
fi

for M in $umount
do
        echo "unmouting $M"
        umount "$M"
done
exit $RET