# Common functions shared by LTSP scripts

die() {
    echo "$@" >&2
    exit 1
}

boolean_is_true(){
    case $1 in
       # match all cases of true|y|yes
       [Tt][Rr][Uu][Ee]|[Yy]|[Yy][Ee][Ss]) return 0 ;;
       *) return 1 ;;
    esac
}

# list files in a directory consisting only of alphanumerics, hyphens and
# underscores
# $1 - directory to list
# $2 - optional prefix to limit which files are selected
run_parts_list() {
    if [ $# -lt 1 ]; then
        echo "ERROR: Usage: run_parts_list <dir>" > /dev/stderr
        exit 1
    fi
    if [ ! -d "$1" ]; then
        echo "ERROR: Not a directory: $1" > /dev/stderr
        exit 1
    fi

    find -L "$1" -mindepth 1 -maxdepth 1 -type f -name "$2*" | sed -n '/.*\/[0-9a-zA-Z_\-]\{1,\}$/p' | sort -n
}

detect_vendor() {
    if [ -e /etc/sysconfig/ltspdist ]; then
        . /etc/sysconfig/ltspdist
        echo "$VENDORDEF"
    else
        echo $(lsb_release --id --short | tr " " "_")
    fi
}

require_root()
{
    if [ ${UID:-$(id -u)} -ne 0 ]; then
        die "Superuser privileges are needed."
    fi
}

# Remember mounted dirs so that it's easier to unmount them with a single call
# to umount_marked. They'll be unmounted in reverse order.
# Use the normal mount syntax, e.g.
#   mark_mount -t proc proc "$ROOT/proc"
mark_mount() {
    local dir

    # The last parameter is the dir we need to remember to unmount
    dir=$(eval "echo \$$#")
    if mount "$@"; then
        # Use newlines to separate dirs, in case they contain spaces
        if [ -z "$MARKED_MOUNTS" ]; then
            MARKED_MOUNTS="$dir"
        else
            MARKED_MOUNTS="$dir
$MARKED_MOUNTS"
        fi
    else
        die "Could not mount $dir."
    fi
}

umount_marked() {
    [ -z "$MARKED_MOUNTS" ] && return

    echo "$MARKED_MOUNTS" | while read dir; do
        # binfmt_misc might need to be unmounted manually, see LP #534211
        if [ "$dir%/proc}" != "$dir" ] && 
            ( [ "$VENDOR" = "Debian" ] || [ "$VENDOR" = "Ubuntu" ] ) &&
            [ -d "$dir/sys/fs/binfmt_misc" ] && [ -f "$dir/mounts" ] &&
            grep -q "^binfmt_misc $dir/sys/fs/binfmt_misc" "$dir/mounts"; then
            if ! umount "$dir/sys/fs/binfmt_misc"; then
                echo "Couldn't unmount $dir/sys/fs/binfmt_misc." >&2
            fi
        fi
        if ! umount "$dir"; then
            echo "Couldn't unmount $dir." >&2
        fi
    done
}

if [ -f /usr/share/ltsp/ltsp-vendor-functions ]; then
    . /usr/share/ltsp/ltsp-vendor-functions
fi
