#!/bin/bash
# LibreChRoot
# Enters a chroot

# Copyright 2010 Nicolás Reynolds
# Copyright 2011 Joshua Haase

# ---------- GNU General Public License 3 ----------

# This file is part of Parabola.

# Parabola is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.

# Parabola is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.

# You should have received a copy of the GNU General Public License
# along with Parabola. If not, see <http://www.gnu.org/licenses/>.

function usage {

    echo ""
    echo "Usage: $0 [options] [chrootname]"
    echo "Use it as root."
    echo ""
    echo "Default chroot name: $CHROOT"
    echo "Default chrootdir: $CHROOTDIR"
    echo ""
    echo "OPTIONS:"
    echo ""
    echo " -c : clean the chroot using pacman"
    echo "      only 'base', 'base-devel' and 'sudo' on chroot"
    echo " -d <chrootdir> : use <chrootdir> instead of default"
    echo " -r : clean /repo on the chroot"
    echo " -h : this message"
    echo " -u : update the chroot"
    echo ""

}

function clean_chroot {  # Clean packages with pacman
    cp -a "$(dirname $0)/chcleanup" "${CHROOTDIR}/${CHROOTNAME}/clean"

    mkarchroot -r "cd /build; /clean" "${CHROOTDIR}/${CHROOTNAME}"
}

function clean_repo {
    msg "Cleaning repo for chroot: ${CHROOTDIR}/${CHROOTNAME}"
    if [ -d "${CHROOTDIR}/${CHROOTNAME}/repo" ]; then
        find "${CHROOTDIR}/${CHROOTNAME}/repo/" -mindepth 1 -delete
    else
        mkdir -p "${CHROOTDIR}/${CHROOTNAME}/repo"
    fi
    bsdtar -czf "${CHROOTDIR}/${CHROOTNAME}/repo/repo.db.tar.gz" -T /dev/null
    ln -s "repo.db.tar.gz" "${CHROOTDIR}/${CHROOTNAME}/repo/repo.db"
}
source /etc/libretools.conf

if [ -e "$XDG_CONFIG_HOME/libretools/libretools.conf" ]; then
    source "$XDG_CONFIG_HOME/libretools/libretools.conf"
fi

CLEANCHROOT='false'
UPDATE='false'
CLEANREPO='false'
CHROOTNAME="${CHROOT:-${SUDO_USER:-root}}"

while getopts 'hrcud:' arg; do
    case $arg in
        h) usage; exit 0 ;;
        c) CLEANCHROOT='true' ;;
        u) UPDATE='true' ;;
        r) CLEANREPO='true' ;;
        d) CHROOTDIR="$(readlink -e $OPTARG)" ;;
    esac
done

[[ "$UID" != "0" ]] && {
    error "This script must be run as root."
    exit 1
}

shift $(($OPTIND - 1))

if [ $# -eq 1 ]; then
    CHROOTNAME="$1"
fi

if "$CLEANREPO"; then
    clean_repo
fi

if "$CLEANCHROOT"; then
    clean_chroot
elif "$UPDATE"; then
    msg "Updating chroot: ${CHROOTDIR}/${CHROOTNAME}"
    mkarchroot -u "${CHROOTDIR}/${CHROOTNAME}"
else
    msg "Entering chroot: ${CHROOTDIR}/${CHROOTNAME}"
    mkarchroot -r "bash" "${CHROOTDIR}/${CHROOTNAME}"
fi

exit 0