# !/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

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}" ; 
     echo "for ${mod1}. Reinstalling this module..." ;
     modprobe -r ${mod1} || modprobe -r ${mod1%-*} || modprobe -r ${mod1%%-*} || modprobe -r ${fw1%%[/-]*} || modprobe -r ${fw1%%/*} || echo "Can not find or dissable module for $fw1" ;
     modprobe    ${mod1} || modprobe    ${mod1%-*} || modprobe    ${mod1%%-*} || modprobe    ${fw1%%[/-]*} || modprobe    ${fw1%%/*} || echo "Can not find or restart module for $fw1" ;
  else
     echo "${fw1} firmware still not found." ; 
  fi ;
done ;

