# ~/.utils/suntracker.sh
 
#!/bin/bash
platform=`uname`
 
begin_day='Mar 12'
end_day='Nov 11'
mycity=dallas
 
# begin date/time checks
times=`curl -s "https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20weather.forecast%20where%20woeid%20in%20(select%20woeid%20from%20geo.places(1)%20where%20text%3D%22nome%2C%20$mycity%22)&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys" | jq -r '.query.results[].astronomy'`
sunrise=`echo $times | jq -r '.sunrise'`
sunrise_hour=`echo $sunrise | awk '{print $1}' | tr ':' ' ' | awk '{print $1}'`
sunrise_minute=`echo $sunrise | awk '{print $1}' | tr ':' ' ' | awk '{print $2}'`
sunset=`echo $times | jq -r '.sunset'`
sunset_hour=`echo $sunset | awk '{print $1}' | tr ':' ' ' | awk '{print $1}'`
sunset_minute=`echo $sunset | awk '{print $1}' | tr ':' ' ' | awk '{print $2}'`
current_year=`date +%Y`
current_month=`date +%b`
current_day=`date +%d`
offset_setting=`date +%z | cut -c3`
sunrise_day=$current_day
sunset_day=$current_day
current_epoch=`date +%s`
begin_date=$begin_day
end_date=$end_day
 
# retrieve epoch for daylight savings
if [ "$platform" == "Darwin" ]; then
  begin_epoch=`date -jf "%b %d %Y" "$begin_date" +%s`
  end_epoch=`date -jf "%b %d %Y" "$end_date" +%s`
fi
if [ $platform == "Linux" ]; then
  begin_epoch=`date --date="$begin_date" +%s`
  end_epoch=`date --date="$end_date" +%s`
fi
 
if [ "$current_epoch" -ge "$begin_epoch" -a "$current_epoch" -le "$end_epoch" ]; then
  offset=5
else
  offset=6
fi
((offset=offset-offset_setting))
((sunrise_hour_adj=sunrise_hour+offset+1))
((sunset_hour_adj=sunset_hour+offset+11))
if [ "$sunset_hour_adj" -gt 23 ]; then
  ((sunset_hour_adj=sunset_hour_adj-24))
  ((sunset_day=current_day+1))
fi
 
sunrise_str=$sunrise_hour_adj':'$sunrise_minute' '$current_month' '$sunrise_day
sunset_str=$sunset_hour_adj':'$sunset_minute' '$current_month' '$sunset_day
 
echo "sed -i -- 's/dark/light/g' ~/.yadr/vim/settings/yadr-appearance.vim" | at $sunrise_str
echo "sed -i -- 's/light/dark/g' ~/.yadr/vim/settings/yadr-appearance.vim" | at $sunset_str
 
if [ "$?" != 0 ]; then
  sed -i -- 's/light/dark/g' ~/.yadr/vim/settings/yadr-appearance.vim
fi
 
if [ ! -e ~/.suntracker ]; then
  touch ~/.suntracker
  if [ "$platform" == "Darwin" ]; then
    sunrise_epoch=`date -jf "%H:%M %b %d" "$sunrise_str" +%s`
    sunset_epoch=`date -jf "%H:%M %b %d" "$sunset_str" +%s`
  fi
  if [ "$platform" == "Linux" ]; then
    sunrise_epoch=`date --date="$sunrise_str" +%s`
    sunset_epoch=`date --date="$sunset_str" +%s`
  fi
  if [ "$current_epoch" -ge "$sunrise_epoch" -a "$current_epoch" -le "$sunset_epoch" ]; then
    sed -i -- 's/dark/light/g' ~/.yadr/vim/settings/yadr-appearance.vim
  else
    sed -i -- 's/light/dark/g' ~/.yadr/vim/settings/yadr-appearance.vim
  fi
fi
