#!/bin/bash

get_mods_depending_on () {
    local res

    res=$(lsmod | grep -e "^\\<${1}\\>" | awk '{print $4}')
    res=(${res//,/ })

    (( ${#res[*]} )) && printf "%s\n" "${res[@]}"
}

get_mods_depending_on_recursive () {
    local mods queue i_mod i_testmod

    mods=($1 $(get_mods_depending_on $1))
    queue=(${mods[@]})

    while (( ${#queue[*]} )) ; do
        i_mod=${queue[0]}
        queue=(${queue[@]:1})

        for i_testmod in $(get_mods_depending_on ${i_mod}) ; do
            in_array ${i_testmod} ${mods[@]}
            if [ $? != 0 ] ; then
                mods+=(${i_testmod})
                queue+=(${i_testmod})
            fi
        done
    done

    (( ${#mods[*]} )) && printf "%s\n" "${mods[@]}"
}


build ()
{
    # Are we even needed?
    if [ ! -r "/etc/wpa_supplicant/initcpio.conf" ]; then
        echo "There is no wifi config /etc/wpa_supplicant/initcpio.conf; (create and rerun?); exit"
        return 0
    fi

    # wireless modules
    add_checked_modules "/drivers/net/wireless/"

    # make sure loaded modules depending on cfg80211 are included (e.g. iwlmvm)
    local mod
    for mod in $(get_mods_depending_on_recursive cfg80211) ; do
        add_module $mod
    done

    # make sure to add module ccm (needed in some cases)
    add_module ccm

    add_binary "killall"
    add_binary "wpa_supplicant"
    add_binary "ip"
    add_runscript

    add_file "/etc/wpa_supplicant/initcpio.conf" "/etc/wpa_supplicant/initcpio.conf"
}

help ()
{
cat<<HELPEOF
    Enables wifi on boot, for ssh unlocking of disk.
HELPEOF
}
