#!/vendor/bin/sh

########################################################
### init.insmod.cfg format:                          ###
### -----------------------------------------------  ###
### [insmod|setprop|enable/moprobe] [path|prop name] ###
### ...                                              ###
########################################################

if [ $# -eq 1 ]; then
  cfg_file=$1
else
  exit 1
fi

if [ -f $cfg_file ]; then
  while IFS="|" read -r action arg
  do
    case $action in
      "insmod") insmod $arg ;;
      "setprop")
        times=1
        setprop $arg 1
        while [ "$?" -ne 0 ]
        do
          if [ $times -gt 128 ]; then
            break
          fi
          let times++
          setprop $arg 1
        done ;;
      "enable") echo 1 > $arg ;;
      "modprobe")
        insmod_arg=${arg}
        PAGE_SIZE=$(getconf PAGE_SIZE)
        for partition in system_dlkm vendor
        do
          modules_dir_base="/${partition}/lib/modules"
          if [ $PAGE_SIZE -eq 16384 ]; then
            if [ -d "${modules_dir_base}/16k" ]; then
              modules_dir_base="${modules_dir_base}/16k"
            fi
          fi
          for modules_dir in ${modules_dir_base}/*/ ${modules_dir_base}
          do
            last_part=$(basename ${modules_dir})
            if [ "$last_part" == "16k" ]; then
              if [ $PAGE_SIZE -ne 16384 ]; then
                continue
              fi
            fi
            if [ ! -f "${modules_dir}/modules.load" ]; then
              continue
            fi
            case ${insmod_arg} in
              "-b *" | "-b")
                arg="-b $(cat ${modules_dir}/modules.load)" ;;
              "*" | "")
                arg="$(cat ${modules_dir}/modules.load)" ;;
            esac
            modprobe -a -d ${modules_dir} $arg
          done
        done
    esac
  done < $cfg_file

  # ko may hotadd memory causing ramsize to change, so try to update ramsize after all ko are loaded
  memfile="/proc/meminfo_quick"
  if [ -f ${memfile} ]; then
    memtotal=$(cut -F 1 ${memfile})
    setprop sys.vivo.project.ramsize $(($memtotal/1000000+1))
  fi

else
  exit 2
fi

