#!/bin/bash

# wsCXO: get latest weekly status (ws) of CXO
# usage: wsCXO [-n NUMBER] {-h}  
#
# Source: https://chandra.harvard.edu/press/chandraStatus.html?

#-----------------------------------------------------------------------
HELP=;
TF="OUT_cxo_ws.html"; OF=${TF%.*}".txt"
trap "[ -e $TF ] &&  rm $TF ${TF}t $OF ${OF}t" EXIT
#-----------------------------------------------------------------------

while getopts n:h OPTVAL
do
   case $OPTVAL in
	n) NUMBER=$OPTARG;;
        h) HELP=1;;
        *) echo "wsCXO -h for help"; exit -1;;
   esac
done
shift $((OPTIND-1))

if [ $HELP ]; then
  echo  "~weekly(Friday) report of planned observations for CXO"
  echo  "usage:  wsCXO [-n NUMBER] {-h}"
  echo   "-n NUMBER, default .. latest; Example: N=1189 for Jan 8, 2021"
  exit
fi


#-----------------------------------------------------------------------
#The heavy lift!
#-----------------------------------------------------------------------

if [ $NUMBER ]; then 
    curl -s "https://chandra.harvard.edu/press/chandraStatus.html?id=$NUMBER" -o $TF
else
    curl  -s "https://chandra.harvard.edu/press/chandraStatus.html?" -o $TF
fi

#-----------------------------------------------------------------------
#Format for readability: note use of subshells (cf cat line ) & "-s" option
#-----------------------------------------------------------------------

gsed -it 's;<p>;\n;g' $TF
textutil -convert txt $TF 
gsed -it '1,/Operations CXO/d;/Return to/,$d' $OF
cat -s <(fmt <(sed '/^---/,/^---/d' $OF)) <(sed -n '/^--/,/^---/p' $OF)
