#!/sbin/sh
#VenomFileCheck - do not use without permission.
#
#VenomFileCheck.sh <Filename.Prop> <PropSetting> options
#
#<FileExists> <Filename/FolderName>
#<CompareMd5> <Filename> <Md5Value>
#<TextExistsInFile> <Filename> <Text>
#<Sql> <DatabaseFilename> <SqlQuery>
#
sqlite3="/system/xbin/sqlite3"
TempFolder="/tmp"
SettingsFolder="/sdcard/Venom/Settings"
LogFile="$SettingsFolder/VenomTools.log"

/sbin/busybox mount /system
/sbin/busybox mount /data

if ! [ -d $TempFolder ]; then
   mkdir $TempFolder
fi

if ! [ -d $SettingsFolder ]; then
   mkdir $SettingsFolder
fi

if ! [ -d "/tmp" ]; then
   mkdir /tmp
fi

Log()
{
   message="$@"
   echo $message
   echo $message >>$LogFile
}

AddPropSetting()
{
   if [ -f $PropFile ]; then
      sed -i "/^$2/d" $PropFile
   fi
   Log "Setting $2 to $3 in $PropFile"
   Log "$2=$3" >> $PropFile
}

Data=$(ls /data)
Log "Contents of /data: $Data"

if [ -n "$1" -a -n "$2" -a -n "$3" -a -n "$4" ]; then
   PropFile=$TempFolder/$1
   case "$3" in
      FileExists)
         FileExists=0
         if [ -f $4 -o -d $4 ]; then
            FileExists=1
         fi
         AddPropSetting $1 $2 $FileExists
      ;;
      CompareMd5)
         MD5Matches=0
         if [ -f $4 ]; then
            MD5=$(md5sum $4 | cut -d' ' -f1)
         else
            Log "ERROR: $4 doesn't exist"
         fi
         if [[ $MD5 = $5 ]]; then
            MD5Matches=1
         fi
         AddPropSetting $1 $2 $MD5Matches
      ;;
      TextExistsInFile)
         TextExists=0
         if [ -f $4 ]; then
            if grep -Fxq "$5" $4 1>/dev/null; then
               TextExists=1
            fi
         else
            Log "ERROR: $4 doesn't exist."
         fi
         AddPropSetting $1 $2 $TextExists
      ;;
      Sql)
         if [ -f "$sqlite3" ]; then
            if [ -f $4 ]; then
               if [ -n "$5" ]; then
                  Log "Filename: $4"
                  Log "$sqlite3 $4 \"$5\""
                  SqlQueryResult=$($sqlite3 $4 "$5")
                  HasRows=0
                  if [ -n "$SqlQueryResult" ]; then
                     HasRows=1
                  fi
                  AddPropSetting $1 $2 $HasRows
               else
                  Log "Missing sql query: $5"
               fi
            else
               Log "ERROR: $4 doesn't exist."
            fi
         else
            Log "Can't find $sqlite3"
         fi
      ;;
      *)
         Log "ERROR: Invalid argument: $3"
      ;;
   esac
else
   Log "Usage: CheckFile.sh <PropFile> <PropSetting> <CheckType> <Filename/Folder>"
fi

cp $PropFile /sdcard/Venom/Settings/