#!/bin/bash
# by Dave Taylor of Linux Journal

## localize this, please:

yourzip="96746"         # Kapa'a

function isdaytime
{
  # shell functions return zero on success (true), non-zero on error

  hour=$(date +%H)
  min=$(date +%M)

  # get the sunrise/sunset times in a usable format from almanac.com

  request="http://www.almanac.com/astronomy/rise/zipcode"
  thedate="$(date +%Y-%m-%d)"
  url="$request/$yourzip/$thedate"

  raw="$(/usr/bin/curl --silent "$url" | grep rise_nextprev | cut -d\< -f28-30)"

  sunrise="$(echo $raw | cut -d\  -f2)"; sunset="$(echo $raw | cut -d\  -f4)"

  srh=$(echo $sunrise | cut -d: -f1)            ; srm=$(echo $sunrise | cut -d: -f2)
  ssh=$(( $(echo $sunset | cut -d: -f1) + 12 )) ; ssm=$(echo $sunset | cut -d: -f2)

  # now let's test the current hour/minute against the sunrise/sunset times

  echo "testing current time: $hour:$min against sunrise $srh:$srm and sunset $ssh:$ssm"

  if [ $hour -eq $srh -a $min -ge $srm ] ; then
    return 0	# special case of sunrise hour
  fi
  if [ $hour -gt $srh -a $hour -lt $ssh ] ; then
    return 0	# easy: after sunrise, before sunset
  fi
  if [ $hour -eq $ssh -a $min -le $ssm ] ; then
    return 0    # special case: sunset hour
  fi

  return 1
}

if isdaytime ; then
  echo it is daytime
else
  echo it is nighttime
fi

exit 0



syntax highlighted by Code2HTML, v. 0.9.1