#!/bin/sh

# Empty Frequencies Finder, find free/empty frequencies #
#                                                       #
#           Copyright (c) 2010 BLIZZARD                 #

send_request()
{
  dbus-send --system --print-reply \
            --dest=de.pycage.FMRXEnabler \
            /de/pycage/FMRXEnabler\
            de.pycage.FMRXEnabler.request >/dev/null
}

find_sysfs_path()
{
  F=`find /sys/class/i2c-adapter -name "fm_frequency"`
  echo `dirname ${F}`
}

power_on()
{
  # switch on
  echo 1 >${SYSFS_PATH}/power_state
  # set DAC audio route
  echo 16 >${SYSFS_PATH}/audio_route
  # set stereo
  echo 12 >${SYSFS_PATH}/dac_output
  # set preset tune mode
  echo 1 >${SYSFS_PATH}/fm_search_tune_mode
  # unmute
  echo 0 >${SYSFS_PATH}/mute
}

power_off()
{
  echo "POWERED OFF"
  # mute
  echo 1 >${SYSFS_PATH}/mute
  # switch off
  echo 0 >${SYSFS_PATH}/power_state
}

tune_in()
{
  FREQ=$1
  echo ${FREQ} >${SYSFS_PATH}/fm_frequency
}

change_frq()
{
  send_request
  SYSFS_PATH=`find_sysfs_path`
  power_on
  tune_in $cur_freq
}

#Temporary file for saving empty frequencies
temp=`mktemp -t temp.XXXXXX`

#Print banner
ver="1.4.2"
$prefix run-standalone.sh zenity --info --text="E.F.F. (Empty Frequencies Finder)" --title="E.F.F-$ver"

#Vars
vars()
{
  scale_factor=100
  max=`expr $max \* $scale_factor`
  min=`expr $min \* $scale_factor`
  range=`expr $max - $min`
  if [ $needs_odd_multiples -eq 1 ]
    then
    freq_incr=`expr $scale_factor \* 2`
  else
    freq_incr=$scale_factor
  fi
  pers_var=`expr $range / 100`
  cur_freq=$min
  pers_cntr=0
  cnt_total=0
}

#Change testing frequency, calculate percentage of progress
change_tfrq()
{
  if [ $cur_freq -eq $max ] || [ $cur_freq -gt $max ]
    then
    break
  fi
  pers_cntr=`expr $pers_cntr + 1`
  pers=`expr \( $scale_factor \* $pers_cntr \) / $pers_var`
  cur_freq=`expr $cur_freq + $freq_incr`
  cnt=0
  change_frq
  if [ $guiyn -eq 0 ]
    then
    echo $pers
  else
    if [ $pers -lt 100 ]
      then
      echo "Scanning...Found $cnt_total empty frequencies. $pers %"
    else
      echo "Scanning...Found $cnt_total empty frequencies. 100 %"
    fi
  fi
  sleep 1
  if [ $guiyn -eq 0 ]
    then
    echo "# Scanning...Found $cnt_total empty frequencies"
  fi
}

#How much empty, functions
hempty_a()
{
  if [ $cnt -eq 10 ]
    then
    sleep 1
  fi
}

hempty_b()
{
  if [ $cnt -eq 10 ] || [ $cnt -eq 45 ]
    then
    sleep 1
  fi
}

hempty_c()
{
  if [ $cnt -eq 5 ] || [ $cnt -eq 20 ] || [ $cnt -eq 60 ]
    then
    sleep 1
  fi
}

hempty_d()
{
  if [ $cnt -eq 5 ] || [ $cnt -eq 30 ] || [ $cnt -eq 60 ] || [ $cnt -eq 80 ]
    then
    sleep 1
  fi
}

#Zenity question to be root
#Currently not in use
quest_root()
{
  rans=$(zenity --entry --entry-text="root" --title="To run you must be root, if you agree type OK." --text="Press OK to continue or cancel to quit.")
  if [ $? -eq 0 ]
    then
    eval $rans
  else
    zenity --error --text="You must be root!"
    exit 1
  fi
}

#Check if the frequency is empty
check_frq()
{
  while [ 1 ]
    do
    #unmake the following from comment to is if its working
    #echo "# `cat /sys/class/i2c-adapter/i2c-3/3-0022/fm_frequency` `cat /sys/class/i2c-adapter/i2c-3/3-0022/fm_rssi`"
    #echo "# `echo $hempty $cnt`"
    if [ $cnt -eq `expr 60 \* $hempty` ]
      then
      cnt_total=`expr $cnt_total + 1`
      msg=1
      echo $cur_freq >> $temp
      break
    fi
    case $hempty in
      1)
        hempty_a ;;
      2)
        hempty_b ;;
      3)
        hempty_c ;;
      4)
        hempty_d ;;
    esac
    if [ `cat /sys/class/i2c-adapter/i2c-3/3-0022/fm_rssi` = "-112" ]
      then
      cnt=`expr $cnt + 1`
    else
      break
    fi
    done
}

#Stop with zenity cancel button
zcancel()
{
  if [ $? -eq 1 ]
    then
    power_off
    exit 1
  fi
}

#Message on $temp, function
#Currently not in use!
tmsg()
{
  if [ $guiyn -eq 1 ]
    then
    echo "You searched from $min to $max, with $hempty empty value. Found $cnt_total empty frequencies:"
    cat $temp
  fi
}

#MAIN

#Check if headphones are connected
if [ `cat /sys/devices/platform/gpio-switch/headphone/state` = "disconnected" ]
  then
  $prefix run-standalone.sh zenity --error --title="ERROR" --text="Headphones are not plugged in!"
  exit 1
fi

#Check if zenity is installed
if [ `zenity --version` ]
  then
  echo "You have zenity installed...proceeding"
else
  echo "***YOU DO NOT HAVE ZENITY INSTALLED...ABORTING***"
  exit 1
fi

#Check if is root
if [ `id -u` = "0" ]
  then
  cd /home/user
  hempty=$($prefix run-standalone.sh zenity --scale --min-value=1 --max-value=4 --value=1 --text="Note that higher value requires more scanning time!" --title="Search for: 1=Slightly-empty 2=Empty 3=Very-empty 4=Extremely-empty")
  #Check if user selected a value
  if [ $? -eq 1 ]
    then
    $prefix run-standalone.sh zenity --error --title="ERROR" --text="You must select a value!Aborting..."
    exit 1
  fi
  $($prefix run-standalone.sh zenity --question --title="Region" --text="If you need odd multiples press OK")
  if [ $? -eq 0 ]
    then
    needs_odd_multiples=1
  fi
  #User selects range for scanning
  min=$($prefix run-standalone.sh zenity --scale --min-value=875 --max-value=1080 --value=875 --title="Search from:" --text="Select min value (ex. 991=99.1 , 1034=103.4)")
  zcancel
  if [ $needs_odd_multiples -eq 1 ] && [ `expr $min % 2` -eq 0 ]
    then
    min=`expr $min + 1`
    echo "Minimum value must be odd. Using $min"
  fi
  max=$($prefix run-standalone.sh zenity --scale --min-value=875 --max-value=1080 --value=875 --title="From $min to:" --text="Select max value (ex. 991=99.1 , 1034=103.4)")
  zcancel
  $prefix run-standalone.sh zenity --question --title="Do you want gui during scanning?" --text="If you type "YES" you will not be able to multitask." --ok-label="YES"

  #Asks user if he wants gui or not
  if [ $? -eq 1 ]
    then
    guiyn=1
  else
    guiyn=0
  fi
  vars

  #Check if min value given is greater or equal to mx
  if [ $min -lt $max ]
    then
    #Start scanning process
    if [ $guiyn -eq 0 ]
      then
      (while [ 1 ]
        do
        change_tfrq
        check_frq
        done
      ) | $prefix run-standalone.sh zenity --progress --text="Scanning..." --auto-close
      zcancel
    else
      while [ 1 ]
        do
        change_tfrq
        check_frq
        done
    fi
    #Echo info message
    tmsg
    #List empty frequencies
    $prefix run-standalone.sh zenity --text-info --filename=$temp
    power_off
  else
    $prefix run-standalone.sh zenity --error --text="Max value must be greater than min value!"
  fi
else
  $prefix run-standalone.sh zenity --error --text="You must be root!"
fi
