#!/usr/bin/env bash
PROGNAME="${0##*/}"

# $Id$

set +u
shopt -s xpg_echo

WORKDIR=$HOME/cis/work
RO_PWDFILE=$HOME/cis/ro.password
SUMFILE=linux.sh.md5sum
COOKIEJAR=${PROGNAME%%.*}.cookies
TMPFILE=${PROGNAME%%.*}.tmp  # will hold downloaded file until we checksum it

[ $# -ne 0 ] && {
    echo "SYNTAX:  $PROGNAME" 1>&2
    exit 3
}

Abort() {
    echo "Aborting $PROGNAME:  $*" 1>&2
    exit 2
}

for bin in md5sum curl; do
    type -t $bin >/dev/null ||
    Abort "$PROGNAME requires '$bin' in your search path"
done

FQHN=$(hostname)
case "$FQHN" in *.*);; *) Abort "Our policy requires 'hostname' to be FQ, but we have: $FQHN";; esac
# Any protected URL will work, to redirect (pseudo-) user to the login form page.
# To simplify quoting/escaping, use a URL that has no shell metacharacters (incl. space) in it.
PROTECTED_URL=https://$FQHN/ui/SetupSyncTargetOverview
# This necessary has a shell metacharacter so must be quoted:
SOURCE_URL="https://$FQHN/ui/SetupDiscoveryScriptDownload?platform=Linux"

[ -d "$WORKDIR" ] || {
    mkdir "$WORKDIR" || Abort "Failed to create work directory '$WORKDIR'"
}
cd "$WORKDIR" || Abort "Failed to cd to work directory '$WORKDIR'"

[ -s $RO_PWDFILE ] && {
    ls -ld $RO_PWDFILE | grep -q '^-...------' ||
    echo "Fix permissions with: chmod 0600 $RO_PWDFILE" 1>&2
} ||
echo "Password file missing or empty: $RO_PWDFILE" 1>&2

umask 066   # So observers can't read cookie or platform file
trap 'rm -f $COOKIEJAR' EXIT  # Don't leave vulnerabilities hanging around

# Use $(subshell) instead of Curl @ to get password because @ doesn't allow for
# newlines in the the password file, and that would be very inconvenient.
curl -sS -o $TMPFILE -X POST -k -c $COOKIEJAR  \
  -d 'tw_login_method=GET' -d tw_login_button= -d tw_login_username=ro  \
  --data-urlencode tw_login_password=$(<$RO_PWDFILE) -H "Origin: https://$FQHN"  \
  -H "Referer: $PROTECTED_URL" $PROTECTED_URL ||
Abort "Authentication request failed.  See file '$TMPFILE'"
[ -s $TMPFILE ] || Abort 'Authentication request failed (No output)'
trap 'rm -f $COOKIEJAR $TMPFILE' EXIT  # Don't leave vulnerabilities hanging around

curl -sS -o $TMPFILE -k -b $COOKIEJAR -H "Origin: https://$FQHN" -H "Referer: $PROTECTED_URL" "$SOURCE_URL" ||
Abort 'Fetch request failed'

CHECKSUM=$(md5sum $TMPFILE | sed 's/ .*//;')
[ -s "$SUMFILE" ] && [ "$(<$SUMFILE)" = "$CHECKSUM" ] && exit 0
[ -s "$SUMFILE" ] || {
    echo "$CHECKSUM" > $SUMFILE
    echo 'Starting to monitor platform file checksum'
    exit 0
}
echo "$CHECKSUM" > $SUMFILE
exit 1
