#!/system/bin/sh
#
# Random boot animation
#
# v1.5 General Release (djmcnz)
# - Updated specifically to use large internal data partitions
#
# v1.4 Kang-o-rama (djmcnz)
# - Moved source location to sd-ext to support CM6 boot order
#
# v1.3
# - Updated to work with CM 5.0.6 (push fstab to /system/etc)
# - Added option to specify boot animation to use
# - Added logging output
#
# v1.2
# - Changed filename to 09bootanimation to work with CM 5.0.5.3 Apps2SD
#
# v1.1
# - Enables storage on SD card (thanks godsfilth!)
# - Added error checking for no animation files
#
# V1.0
# - Initial release
  
# specify directory for boot animation files
BA_DIR="/data/local/bootanimations"

if [ ! -d $BA_DIR ]; then
  mkdir $BA_DIR
  chmod -R 0777 $BA_DIR
  log -p i -t bootanimation "bootanimation dir succesfully created."
fi

# check if boot animation is specified
BA_USE=${BA_DIR}"/bootanimation.use"
if [ -e $BA_USE ]; then
  # use file specified in booatnimation.use
  BA_FILE=${BA_DIR}"/"$(cat $BA_USE)

  log -p i -t bootanimation "Using $BA_FILE"
  
  # copy file to /data/local
  cp $BA_FILE /data/local/bootanimation.zip
  
  if [ "$?" = 0 ];
  then
    log -p i -t bootanimation "$BA_FILE successfully copied";
  else
    log -p e -t bootanimation "Error copying $BA_FILE";
  fi

else
  log -p i -t bootanimation "Choosing a random boot animation"
  
  # temp file to hold list of animation files
  BA_TMP=${BA_DIR}"/bootanimation.tmp"
  
  # count number of animation files
  ls ${BA_DIR}/*.zip > $BA_TMP
  BA_COUNT=$(wc -l < $BA_TMP)
  
  if [ $BA_COUNT -gt 0 ];
  then
    # generate 8bit random number, increase if more than 255 animations
    RANDOM=$(hexdump -e '1/1 "%d"' -n 1 /dev/urandom)
    
    # select random file
    BA_NUM=$(($RANDOM % $BA_COUNT + 1))
    BA_FILE=$(sed -n "${BA_NUM}"p ${BA_TMP})
    
    # copy file to /data/local
    cp $BA_FILE /data/local/bootanimation.zip
    
    if [ "$?" = 0 ];
    then
      log -p i -t bootanimation "$BA_FILE successfully copied";
    else
      log -p e -t bootanimation "Error copying $BA_FILE";
    fi

  else
    log -p e -t bootanimation "No boot animation files found";
  fi

  # delete tmp file
  rm $BA_TMP

fi
