#!/bin/bash

### Copyright notice at the bottom of this file ###

# $Id: nthday,v 1.6 2012/01/08 19:15:37 adamm Exp adamm $
#
# $Source: /home/adamm/src/nthday/RCS/nthday,v $

###
### A quick hack to show the Nth day of the month
###

PROG=$(basename $0)


main() {
# Check the command line
if [ $# -ne 2 ] && [ $# -ne 4 ] ; then
    Usage
    exit 2
fi

# Convert day names to numbers
case $2 in
[1-7])		d=$2		;;
[Ss]un)		d=1		;;
[Mm]on)		d=2		;;
[Tt]ue)		d=3		;;
[Ww]ed)		d=4		;;
[Tt]hu)		d=5		;;
[Ff]ri)		d=6		;;
[Ss]at)		d=7		;;
*)		Usage;	exit 2	;;
esac

# Strip leading 0s from the month
if [ $# -eq 4 ] ; then
    m=$(echo $3 | sed 's/^0//')
else
    m=$3
fi

# Rebuild the command line
set $1 $d $m $4

# Grind out an answer, letting "cal" do the hard bits
cal $3 $4 |
sed '/[^0-9 ]/d' |
awk '
BEGIN {
    which = '$1'
    dow = '$2'

    # Seed the indices
    for (i = 1; i <= 7; i++) {
	ix[i] = 1
    }
}
#
{
    # "right-justify" the first line
    if ((NR == 1) && (NF != 7)) {
	n = split("x x x x x x " $0, tmp)
	j = 1
	for (i = NF; i <= n; i++) {
	    $j = tmp[i]
	    ++j
	}
    }

    # Now store the days in their bins
    for (i = 1; i <= NF; i++) {
	if ($i != "x") {
	    days[i, ix[i]] = $i
	    ++ix[i]
	}
    }
}
#
END {
    # Two quick error checks
    if ((dow < 1) || (dow > 7) || (which < 1) || (which > 5)) {
	# Call ourselves in a way guaranteed to produce an error
	# (to avoid duplicating the usage message)
	system("'$0'")
	exit 2
    }

    if (which < ix[dow]) {
	print days[dow, which]
	exit 0
    } else {
	exit 1
    }
}'
} # main


Usage() {
    echo "Usage: $PROG which day [ mon year ]"
    echo
    echo "which = 1..5"
    echo "dow = \"sun\"..\"sat\" (or 1..7)"
    echo "mon = 1..12"
    echo "year = YYYY"
    echo
} # Usage


main "$@"


###
### Copyright, 2012, Adam Moskowitz. All rights reserved.
###
### Any redistribution of this software must retain the above copyright
### notice, this list of conditions, and the following disclaimer.
###
### Without specific prior written permission from the copyright holder,
### you may not charge a fee for the redistribution of this software.
###
### All other redistribution and use is hereby permitted.
###
### This software is provided "as is" and without any express or implied
### warranties, including, without limitation, the implied warranties of
### merchantability and fitness for a particular purpose.
###
