#!/bin/bash

LIBDIR='/usr/lib/manjaro-chrootbuild'

. ${LIBDIR}/util.sh
. ${LIBDIR}/util-chroot.sh

MOUNT=false
UMOUNT=false

trap 'abort "Aborted."' INT
check_root
get_default_branch

while getopts "b:chHk:mu" arg; do
    case "${arg}" in
        b) BRANCH="${OPTARG}" ;;
        c) CLEAN=true ;;
        f) FORCE_UNMOUNT=true ;;
        H) HOST_KEYS=true ;;
        k) custom_repo="${OPTARG}" ;;
        m) MOUNT=true ;;
        M) MIRROR="${OPTARG}" ;;
        u) UMOUNT=true ;;
        h|?) usage_prepare_chroot 0 ;;
        *) usage_prepare_chroot 1 ;;
    esac
done
shift $((OPTIND -1))

if [[ $UMOUNT = true ]]; then
    msg "Unmount Chroot filesystem."
    cleanup
    exit 0
fi

prepare_chroot ${CHROOT_DIR}

if [[ $MOUNT = true ]]; then
    msg "Chroot filesystem of branch [${BRANCH}] is ready and mounted at [${CHROOT_DIR}]."
    msg4 "To unmount run 'prepare_chroot' again with the '-u' flag."
else
    msg "Chroot filesystem of branch [${BRANCH}] has been prepared at [${CHROOT_DIR}]."
    cleanup
fi
