User:Rick Bot/scripts/update maindate

#!/bin/bash

echo "Starting update-maindate"
CURMONTH=`date +%B`
CURYEAR=`date +%Y`
CURDAY=`date +%d`
CURDAY=${CURDAY#0}

function prevmonth () {
  case $1 in
    January) echo "December";;
    February) echo "January";;
    March) echo "February";;
    April) echo "March";;
    May) echo "April";;
    June) echo "May";;
    July) echo "June";;
    August) echo "July";;
    September) echo "August";;
    October) echo "September";;
    November) echo "October";;
    December) echo "November";;
  esac
}

LASTMONTH=`prevmonth $CURMONTH`
LASTMONTHYEAR=$CURYEAR
if [ $LASTMONTH = "December" ]; then
   let LASTMONTHYEAR=$CURYEAR-1
fi

LASTMONTHLASTDAY=31
  case $LASTMONTH in
    January|March|May|July|August|October|December) LASTMONTHLASTDAY=31 ;;
    April|June|September|November) LASTMONTHLASTDAY=30 ;;
    February)
      LASTMONTHLASTDAY=28
      let LEAPYEAR=$LASTMONTHYEAR%4
      if [ $LEAPYEAR -eq 0 ]; then
        LASTMONTHLASTDAY=29
      fi ;;
  esac

echo "Current month and year are $CURMONTH $CURYEAR"
echo "Last day of last month is $LASTMONTH $LASTMONTHLASTDAY $LASTMONTHYEAR"

CURLAST=`tail -1 ./maindate.all`

#make sure last day of last month is in maindate.all

grep "[|][|]..$LASTMONTH $LASTMONTHLASTDAY[], ]*..*$LASTMONTHYEAR..[|][|]" ./maindate.all >/dev/null
if [ $? -ne 0 ]; then
  echo "Last day of last month not in maindate.all, CURLAST=$CURLAST"
  ./maindate $LASTMONTH $LASTMONTHYEAR >/tmp/new.$$
fi

let NEXTDAY=$CURDAY+1
./maindate $CURMONTH $CURYEAR | sed -e "/\[\[$CURMONTH $NEXTDAY\]\]/,\$d" >>/tmp/new.$$
NEWLAST="MAINDATE||`tail -1 /tmp/new.$$`"
if [ "$NEWLAST" != "$CURLAST" ]; then
  # echo new maindates
  echo NEWLAST="$NEWLAST"
  echo CURLAST="$CURLAST"
  # LASTART="${CURLAST##*||}"
  LASTDATE="${CURLAST#*||}"
  LASTDATE=${LASTDATE%||*}
  LASTDATE=`echo $LASTDATE | tr "[]" ".."`
  grep "^${LASTDATE}[|][|]" /tmp/new.$$ >/dev/null
  if [ $? -eq 0 ]; then
    echo Found "$LASTDATE"
    echo first | cat - /tmp/new.$$ | sed -e "1,/^$LASTDATE/d" >/tmp/add.$$
  else
    echo Didnt find "$LASTDATE"
    cat /tmp/new.$$ >/tmp/add.$$
  fi
  echo "Adding the following maindates:"
  cat /tmp/add.$$ 
  cat /tmp/add.$$ | sed -e "s/^/MAINDATE||/" >>./maindate.all
fi

awk '

BEGIN {
  FS="\\|\\|"
  OFS="||"
  while ( getline <"featureds" ) {
    featured[$2] = 1
  }
  while ( getline <"formers" ) {
    former[$2] = 1
  }
  while ( getline <"maindate.all" ) {
    if (featured[$3] != 1 && former[$3] != 1 && $3 != "Provinces of Thailand" && $3 != "History of South Carolina") {
      printf "%s",  "*** Maindate, but not FA or FFA: " $3 ": "
      getline art
      if (art != "") {
         $3 = art
      }
    }
    print $0 >"maindate.new"
  }
  exit
}'

cp maindate.all maindate.old
cp maindate.new  maindate.all
rm maindate.new
# rm -f /tmp/new.$$
# rm -f /tmp/add.$$