# Fedora-specific function overrides for the common functions

detect_arch() {
    echo $(uname -m | sed -e s/i.86/i386/)
}

if [ -z "$HOSTNAME" ] || [ "$HOSTNAME" = "localhost.localdomain" ] || [ "$HOSTNAME" = "localhost" ]; then
    HOSTNAME_BASE=${HOSTNAME_BASE:-ltsp}
    IPV4ADDR=$(ip -4 a s $DEVICE |awk 'sub(/\/24/, ""){print $2}')
    IPV4NETMASK=$(ip -4 a s $DEVICE |awk 'sub(/\/24/, ""){print $4}')
    case "$HOSTNAME_EXTRA" in
        mac)
            HOSTNAME_EXTRA=$(ip link show $DEVICE | awk '/ether/{print $2}' | tr ':' '-')
            ;;
        ip|"")
            HOSTNAME_EXTRA=$(echo "$IPV4ADDR.$IPV4NETMASK" | awk -F "." '{ print (($1%(256-$5)*256+$2%(256-$6))*256+$3%(256-$7))*256+$4%(256-$8) }')
            ;;
    esac
    HOSTNAME="$HOSTNAME_BASE$HOSTNAME_EXTRA"
fi

# Taken from dracut lib
# returns OK if $1 contains $2
strstr() {
  [ "${1#*$2*}" != "$1" ]
}

getarg() {
    set +x
    local o line
    if [ -z "$CMDLINE" ]; then
        if [ -e /etc/cmdline ]; then
            while read line; do
                CMDLINE_ETC="$CMDLINE_ETC $line";
            done </etc/cmdline;
        fi
        read CMDLINE </proc/cmdline;
        CMDLINE="$CMDLINE $CMDLINE_ETC"
    fi
    for o in $CMDLINE; do
        [ "$o" = "$1" ] && { [ "$RDDEBUG" = "yes" ] && set -x; return 0; }
        [ "${o%%=*}" = "${1%=}" ] && { echo ${o#*=}; [ "$RDDEBUG" = "yes" ] && set -x; return 0; }
    done
    [ "$RDDEBUG" = "yes" ] && set -x
    return 1
}

getargs() {
    set +x
    local o line found
    if [ -z "$CMDLINE" ]; then
        if [ -e /etc/cmdline ]; then
            while read line; do
                CMDLINE_ETC="$CMDLINE_ETC $line";
            done </etc/cmdline;
        fi
        read CMDLINE </proc/cmdline;
        CMDLINE="$CMDLINE $CMDLINE_ETC"
    fi
    for o in $CMDLINE; do
        [ "$o" = "$1" ] && { [ "$RDDEBUG" = "yes" ] && set -x; return 0; }
        if [ "${o%%=*}" = "${1%=}" ]; then
            echo -n "${o#*=} ";
            found=1;
        fi
    done
    [ -n "$found" ] && { [ "$RDDEBUG" = "yes" ] && set -x; return 0; }
    [ "$RDDEBUG" = "yes" ] && set -x
    return 1;
}

nfsroot_to_var() {
    # strip nfs[4]:
    local arg="$@:"
    nfs="${arg%%:*}"
    arg="${arg##$nfs:}"

    # check if we have a server
    if strstr "$arg" ':/*' ; then
        server="${arg%%:/*}"
        arg="/${arg##*:/}"
    fi

    path="${arg%%:*}"

    # rest are options
    options="${arg##$path}"
    # strip leading ":"
    options="${options##:}"
    # strip  ":"
    options="${options%%:}"

    # Does it really start with '/'?
    [ -n "${path%%/*}" ] && path="error";

    #Fix kernel legacy style separating path and options with ','
    if [ "$path" != "${path#*,}" ] ; then
        options=${path#*,}
        path=${path%%,*}
    fi
}

[ -z "$root" ] && root=$(getarg root=)
[ -z "$netroot" ] && netroot=$(getarg netroot=)
[ -z "$nfsroot" ] && nfsroot=$(getarg nfsroot=)
[ -z "$nbdroot" ] && nbdroot=$(getarg nbdroot=)


