#!/bin/sh 
#
#
####################################################################
## This script creates repo submision directories in /tce/submit/ ##
## & creates working directories in /tce/optional/                ##
## & downloads the git repo of new  firemware in ~/firmware_git   ##
####################################################################


#############################################################
## Comment or Uncomment main functions as needed at        ##
## script End, otherwise allow to run in this order        ##
#############################################################

. /etc/init.d/tc-functions

#############################################################
## Package Date - Set as needed                            ##
## repo path - Set tc version as needed !!                 ##
#############################################################

date="2017/03/17"
maintainer="coreplayer2"
tce_dir=/etc/sysconfig/tcedir
op=${tce_dir}/optional
tczStore=$(readlink -f $op)
repo="http://tinycorelinux.net/7.x/x86/tcz/"
submitDir="/mnt/sda2/tc7-x86/submit"

clear
#set -x


f_prep(){
#############################################################
## PROCESSING means:                                       ##
## Creating submit directories &                           ##
## downloading info files &                                ##
## downloading dep files if any exist &                    ##
## downloading old firmware extensions into tce/optional   ##
## for any missing files                                   ##
#############################################################



directoryList="\
firmware \
firmware-amd-ucode \
firmware-amdgpu \
firmware-atheros \
firmware-broadcom_bcm43xx \
firmware-broadcom_bnx2 \
firmware-broadcom_bnx2x \
firmware-chelsio \
firmware-i915 \
firmware-intel_e100 \
firmware-intel \
firmware-ipw2100 \
firmware-ipw2200 \
firmware-iwimax \
firmware-iwlwifi \
firmware-libertas \
firmware-moxa \
firmware-mrvl \
firmware-mwl8k \
firmware-myri10ge \
firmware-netxen \
firmware-nvidia \
firmware-openfwwf \
firmware-qca \
firmware-radeon \
firmware-ralinkwifi \
firmware-rtl8192ce_se_de \
firmware-rtl_bt \
firmware-rtl_nic \
firmware-rtlwifi \
firmware-ti-connectivity \
firmware-tigon \
firmware-ueagle-atm \
firmware-vxge \
firmware-zd1211"


[ "$PWD" =  /mnt/sda2/tc7-x86/submit ] || cd $submitDir
[ -d "$submitDir" ] || exit 1

for f in $directoryList; do
        [ -d "${submitDir}/${f}" ] || mkdir -p ${submitDir}/${f}
        cd ${submitDir}/${f}
        [ "x$?" = x0 ] || exit 2
set +x
echo -e "\n${BLUE} We are processing ${WHITE}${f}${NORMAL}"
set -x
	[ -f "${tczStore}/${f}.tcz" ] || wget ${repo}/${f}.tcz -O ${tczStore}/${f}.tcz
	[ -f "${f}.tcz.dep" ] || wget ${repo}/${f}.tcz.dep 2>/dev/null
	[ -f "${f}.tcz.info" ] || wget ${repo}/${f}.tcz.info

        if [ -f "${f}.tcz" ]; then
             [ -f ${tczStore}/${f}.tcz ] || mv ${f}.tcz ${tczStore}/${f}.tcz
        fi
        cd ${submitDir}
done
}

#############################################################
## Unpacking Extensions                                    ##
#############################################################

f_unpack(){
[ "$PWD" ==  "${tczStore}" ] || cd $tczStore

set +x

tczFiles=$(find . -iname "firmware*.tcz") 

for t in $tczFiles; do

        d=$(echo ${t##*/})
        if [ ! -d "${d%.*}" ]; then
          echo -e "\n\n\n${MAGENTA} unpacking ${WHITE}${t##*/} ${NORMAL}\n"
          set -x
          unsquashfs -d ${d%.*} ${t##*/}
        fi

        licensePath="${tczStore}/${d%.*}/usr/local/share/doc/License"
        if [ ! -d ${tczStore}/${d%.*}/usr/local/share/doc/License ]; then
          mkdir -p $licensePath
          find ${tczStore}/${d%.*} -name "LICEN*" -exec mv -it ${licensePath}/ {} +
        fi
        echo "\n\n"
done
}

#############################################################
## Downloading new firmware blobs from git                 ##
#############################################################

f_download_source(){
# read -p "waiting..1"
if [ ! -d ~/firmware_git ]; then
    mkdir -p ~/firmware_git
    [ "$PWD" == ~/firmware_git ] || cd ~/firmware_git

    git clone git://git.kernel.org/pub/scm/linux/kernel/git/firmware/linux-firmware.git
    [ "x$?" = x0 ] || echo "Error downloading from git.."
else
    echo "Error! Please remove existing firmware_git dir"
fi
}


#############################################################
## Info file update                                        ##
#############################################################

f_infoFileUpdate(){
[ "$PWD" ==  "$submitDir" ] || cd $submitDir
[ -d "$submitDir" ] || exit 1

for d in firmware*; do

	echo "${d}"
        cd ${submitDir}/${d}
	echo "Current:        ${date} Updated firmware by $maintainer" >> ${d}.tcz.info
        cd ${submitDir}
done
}



#############################################################
## Updating existing firmware blobs from git - WIP         ##
#############################################################

f_mergeBlobs(){                                         #move new blobs function
[ "$PWD" == "${source}" ] || cd $source                #check current path 
for b in $(find . -type f -maxdepth 1); do             #search for firmware in source 
 testDest=$(echo "${dest}/${b##*/}")                   #resolve extension file name, then test it
  if [ -e "${testDest/\/firmware-*\//firmware-${innerDir##*/}}" ]; then
   set +x
    echo "${b##*/}          moved > $dest" >> ${source}/filesMoved_${innerDir##*/}.txt
#    echo "testCopy ${source}/${b##*/}  >  ${dest}/${b##*/}"
    mv -f ${source}/${b##*/} ${dest}/${b##*/}
  fi
done
for r in ${source}/*; do 
  case $r in
       '*Moved*txt' ) continue ;;
                  * ) echo "$r        moved > $dest" >> ${source}/filesMoved_${innerDir##*/}.txt ;; 
  esac
done
find ${source} -type f ! -iname "*Moved*txt" -exec mv -it ${dest}/ {} +
}


f_updateDuplicates(){
unset $d
unset $i
unset $b

[ "$PWD" == "${tczStore}" ] || cd $tczStore            #check current path
for i in $(find . -type d -maxdepth 1 -iname "firmware*"); do     #search for firmware dirs
 echo "checking destination firmware dirs"
  case ${i##*/} in                                     #blacklisted extensions requiring manual update
         firmware ) continue ;;                        #manual update will not be limited to these..
         firmware-chelsio ) continue ;;
         firmware-openfwwf ) continue ;;
         firmware-broadcom* ) continue ;;
         firmware-b43 ) continue ;;
         firmware-rtl8192ce_se_de ) continue ;;
         firmware-zd1211 ) continue ;;
         firmware-atheros ) continue ;;
         firmware-nvidia ) continue ;;
         firmware-carl9170fw ) continue ;;
  esac

 echo -e "\n Entering ${i##*/}"
   set -x
    extFirmwarePath="$tczStore/${i##*/}/usr/local/lib/firmware"
    cd "$extFirmwarePath"                              #enter main library dir
     innerDir1=$(find . -type d -maxdepth 1)           #search for blob specific directories
     innerDir=$(echo ${innerDir1//./})                 #remove path dots
      if [ ! -z ${innerDir##*/} ]; then                #test for cleaned dir name
       cd ${innerDir##*/}                              #enter destination dir
       dest="${extFirmwarePath}/${innerDir##*/}"       #set destination path with inner dir
       source=$(echo ~/firmware_git/linux-firmware/${innerDir##*/})     #set source path with inner dir
       f_mergeBlobs
      else
       continue                                         #Only same named dir to dir comparisons are allowed at present
      fi
sleep 1
# read -p "waiting..."
done
echo -e "\n{YELLOW} Check remaining firmware and License files in source dirs for manual update. \
 Don't forget to check the info files..{NORMAL}"
}


#############################################################
## Comment or Uncomment main functions as needed           ##
## otherwise allow to run in this order                    ##
#############################################################

 f_prep
 f_unpack
 f_download_source
 f_infoFileUpdate
 f_updateDuplicates


#############################################################
#############################################################
set +x
exit
