# *-*-shell-*-*
# vim: set ts=4 sw=4 et:

msg() {
    # bold
    printf "\033[1m=> $@\033[m\n"
}

msg_ok() {
    # bold/green
    printf "\033[1m\033[32m OK\033[m\n"
}

msg_error() {
    # bold/red
    printf "\033[1m\033[31mERROR: $@\033[m\n"
}

msg_warn() {
    # bold/yellow
    printf "\033[1m\033[33mWARNING: $@\033[m\n"
}

emergency_shell() {
    echo
    echo "Cannot continue due to errors above, starting emergency shell."
    echo "When ready type exit to continue booting."
    /bin/sh -l
}

detect_container() {
    # LXC, podman
    [ -z "${container+x}" ] || export IS_CONTAINER=1
    [ -e /.dockerenv ] && export IS_CONTAINER=1

    # backcompat
    [ -n "$IS_CONTAINER" ] && export VIRTUALIZATION=1
}

deactivate_vgs() {
    _group=${1:-All}
    if [ -x /sbin/vgchange -o -x /bin/vgchange ]; then
        vgs=$(vgs|wc -l)
        if [ $vgs -gt 0 ]; then
            msg "Deactivating $_group LVM Volume Groups..."
            vgchange -an
        fi
    fi
}

deactivate_crypt() {
    if [ -x /sbin/dmsetup -o -x /bin/dmsetup ]; then
        msg "Deactivating Crypt Volumes"
        for v in $(dmsetup ls --target crypt --exec "dmsetup info -c --noheadings -o open,name"); do
            [ ${v%%:*} = "0" ] && cryptsetup close ${v##*:} && msg "[crypt] successfully closed: ${v##*:}"
        done
        deactivate_vgs "Crypt"
    fi
}
