#!/bin/bash

# background-changer: changes backgrounds (switches wallpapers)

#
# CONFIGURATION SECTION BEGINS HERE
#

Latitude="51.110000N"
Longitude="17.022222E"

Black="$HOME/.wmbackground/wallpaper-black.png"
Gray="$HOME/.wmbackground/wallpaper-gray.png"
White="$HOME/.wmbackground/wallpaper-white.png"

Gap="15 minutes"

Sunwait="`which sunwait`"

#
# CONFIGURATION SECTION ENDS HERE
#

if [ "$Sunwait" == "" ]
then
    echo "background-changer: install sunwait program."
    exit
fi

now=`date +"%H%M"`
sunrise=`$Sunwait -p $Latitude $Longitude | grep 'Sun rises' | awk '{print $3}'`
sunset=`$Sunwait -p $Latitude $Longitude | grep 'Sun rises' | awk '{print $6}'`

before_sunrise=`date --date="$sunrise -$Gap" +"%H%M"`
after_sunrise=`date --date="$sunrise +$Gap" +"%H%M"`
before_sunset=`date --date="$sunset -$Gap" +"%H%M"`
after_sunset=`date --date="$sunset +$Gap" +"%H%M"`

display=`finger | grep \(:[0-9] | grep -m1 $USER | sed -E 's/.*\(//;s/\)//'`

if [ "$display" == "" ]
then
    if [ "$runner" == "cron" ] || [ "$runner" == "at" ]
    then
	exit
    fi
fi

if [ "$display" != "" ]
then
    display="-display $display"
fi

if [ "$Gray" == "" ]
then
    if [ "$now" -ge "$sunrise" ] && [ "$now" -lt "$sunset" ]
    then
	wmsetbg $display $White
    elif [ "$now" -ge "$sunset" ] || [ "$now" -lt "$sunrise" ]
    then
	wmsetbg $display $Black
    fi
elif [ "$Gray" != "" ]
then
    if [ "$now" -ge "$before_sunrise" ] && [ "$now" -lt "$after_sunrise" ]
    then
	wmsetbg $display $Gray
    elif [ "$now" -ge "$after_sunrise" ] && [ "$now" -lt "$before_sunset" ]
    then
	wmsetbg $display $White
    elif [ "$now" -ge "$before_sunset" ] && [ "$now" -lt "$after_sunset" ]
    then
	wmsetbg $display $Gray
    elif [ "$now" -ge "$after_sunset" ] || [ "$now" -lt "$before_sunrise" ]
    then
	wmsetbg $display $Black
    fi
fi

