# !/bin/bash
#
# Example of message until mid-2016:
# Jun 02 06:55:29 nohostname kernel: iwlwifi 0000:03:00.0: request for firmware file 'iwlwifi-6000g2a-5.ucode' failed.
#
# Example of message after mid-2016:
# Sep 18 20:45:50 nohostname kernel: iwlwifi 0000:03:00.0: Direct firmware load for iwlwifi-6000g2a-5.ucode failed with error -2

mod_tested=" ";

echo "Searching for firmware, that wasn't found during boot, but exist..."

mod_and_fw="$(export=cat journalctl -k | grep -P "firmware .* failed" | sed -re "s/.* kernel: //" -e "s/request for firmware file//" -e "s/Direct firmware load for//" -e "s/[\']* failed.*//" -e "s/ [^ ]*[ ]*[\']*/ /" -e "s/ .*\// /")" ;
fw=$(echo "${mod_and_fw}" | sed -re "s/^[^ ]* //" ) ;
for fw1 in $fw ; 
  do fw1f=$(find /lib/firmware/ -name ${fw1} -type f -print ) ;  
  if [ -f "$fw1f" ] ; then 
     mod1=$(echo "$mod_and_fw" | grep "${fw1}" | sed -re "s/ [^ ]*$//") ;
     echo "\"$fw1\" firmware now found as \"${fw1f}\"" ; 
     if [ -z "$(echo " $mod_tested " | grep " ${mod1} ")" ] ; then
        echo "for \"${mod1}\". Reinstalling this module..." ;
        mod_fails=false;
        modprobe -r ${mod1} || modprobe -r ${mod1%-*} || modprobe -r ${mod1%%-*} || modprobe -r ${fw1%%[/-]*} || modprobe -r ${fw1%%/*} || mod_result=true ;
        modprobe    ${mod1} || modprobe    ${mod1%-*} || modprobe    ${mod1%%-*} || modprobe    ${fw1%%[/-]*} || modprobe    ${fw1%%/*} || mod_result=true ;
        if $mod_fails ; then 
           echo "Can not find, dissable or restart \"${mod1}\" module for \"$fw1\"" ;
        fi ;
        # Remember module as already tested
        mod_tested="$mod_tested ${mod1}";
     else
        echo "but we already tried to reinstall \"${mod1}\" module..." ;
     fi ;
  else
     echo "\"${fw1}\" firmware still not found." ; 
  fi ;
done ;

