#!/bin/bash

#
# No Copyright
#
# The person who associated a work with this deed has dedicated the work to the public domain by waiving all of his or her rights to the work worldwide under copyright law, including all related and neighboring rights, to the extent allowed by law.
#
# You can copy, modify, distribute and perform the work, even for commercial purposes, all without asking permission.
#
# See https://creativecommons.org/share-your-work/public-domain/cc0/ for more information on the license.
#

#
# This is the source code for a musical alarm clock script.
# written by Maarten Tromp <maarten@geekabit.nl>
#
# More info on the project: https://www.geekabit.nl/projects/musical-alarm-clock-script/
#

# $0 = program name
# $1 = [set|sleep|alarm]
# $2 = time for 'set' command

AUMIXOPTS="-d /dev/mixer -v" # v=master, w=pcm, W=pcm2

case "$1" in
	set)
		if [ -n "$2" ] ; then
			echo "$0 alarm" | at $2
		else
			echo "Usage: $0 set <time>"
			exit 1
		fi
		;;


	sleep)
		# _____
		#      \
		#       \
		#        |
		# first:  wait
		# second: fade out music slowly
		# third:  stop playing music


		echo -n "sleeping"

		# first: wait
		if [ -n "$2" ] ; then
			echo -n " ${2} minutes"
			sleep ${2}m
		else
			echo -n " 5 minutes"
			sleep 5m
		fi
		echo

		# second: fade out music slowly
		echo -n "fading"
		for((i=0; i<100; i++)); do
			echo -n "."
			aumix $AUMIXOPTS -
			sleep 30
		done
		echo

		# third: stop playing music
		echo -n "stop"
		xmms --stop
		echo
		;;


	alarm)
		#    _____
		#   /
		#  /
		# |
		# first:  put volume all the way down
		# second: start playing music
		# third: fade in

		# first: put volume all the way down
		aumix $AUMIXOPTS 0

		# second, start playing music, enable repeat
		xmms --play --toggle-repeat=on &

		# third: fade in music quickly to 75%
		for((i=0; i<75; i++)); do
			aumix $AUMIXOPTS +
			sleep 1
		done
		# now slowly fade to max
		for((i=0; i<25; i++)); do
			aumix $AUMIXOPTS +
			sleep 2
		done
		;;


	*)
		# no options, display usage
		echo "Usage: $0 {set|sleep}"
		exit 1
		;;
esac

exit 0
