#!/bin/bash

if [[ -d $XDG_CACHE_HOME ]]
then
  cd -- "$XDG_CACHE_HOME"
fi
# Use a subdirectory to save images of the moon. It's interesting to cycle
# through them with feh to see it move.
mkdir -p luna


function display_help()
{
  echo "usage: $0 <refresh|show|clear|browse|help>"
  echo "  refresh - download current image of the moon"
  echo "  show - create composite background with last image of the moon"
  echo "  reset - reset the background"
  echo "  purge - remove all downloaded images"
  echo "  browse - browse cached images of the moon"
  echo "options: edit the script to change composition parameters"
  echo "         see http://www.imagemagick.org/Usage/compose/ for help"
  echo "dependencies: feh, imagemagick, wget"
}

if [[ -z $1 ]]
then
  display_help
  exit 1
fi

# Path to the composite image.
comp_img=luna/bg.jpg

if [[ ! -f ~/.fehbg ]]
then
  echo "~/.fehbg does not exist"
  exit 1
fi
eval "fehbg=($(cat ~/.fehbg))"
n=${#fehbg[@]}

# The original background image.
bg_img="${fehbg[--n]}"

# Update the command to use the composite image and avoid overwriting ~/.fehbg.
fehbg[n++]="--no-fehbg"
fehbg[n++]="$comp_img"




# Create new bg image with current image of moon.
function refresh()
{
  moon_img="luna/moon-$(date +'%Y.%m.%d.%H.%M.%S.png')"
  curl 'http://api.usno.navy.mil/imagery/moon.png' | convert -trim - "$moon_img"
  composite -compose Screen -gravity northeast "$moon_img" "$bg_img" "$comp_img"
  "${fehbg[@]}"
}


while [[ -n $1 ]]
do
  case "$1" in
    refresh)
      refresh
    ;;

    show)
      if [[ -f $comp_img ]]
      then
        "${fehbg[@]}"
      else
        refresh
      fi
    ;;

    reset)
      source ~/.fehbg
    ;;

    purge)
      rm luna/moon-*.png
    ;;

    browse)
      shift
      feh luna/moon-*.png "$@"
      break
    ;;

    -h | --help | help)
      display_help
      exit 0
    ;;

    *)
      display_help
      exit 1
    ;;
  esac
  shift
done
