#!/bin/bash

# gcloud auth activate-service-account --key-file=/etc/wallet/gcs_wallet_user_serviceaccount.json
# (or -k "blahblah")
# gsutil ls -l gs://$project-uit-authnz-wallet-backup/$envir/wallet-db
# gsutil ls -l gs://$project-uit-authnz-wallet-backup/$envir/wallet-db | grep "\.0.tar.gz"

#### Note: command must be run by an account or service principal with remctl wallet access
daysec=86400
daysec2=172800
backup=""
backupd=""
backupepoch=""

# default thresholds go here
projectd="stage"
envird="dev"
keyfiled="/etc/wallet/gcs_wallet_user_serviceaccount.json"
nagios_servers=""
passive=0
#critd=_____
# fixed conditionals

# describe your check for output and perf
description="wallet backup test"
itemname="wallet_backup"

function usage () {
cat <<-USAGE
    Usage: $0  [-e <environment>] [-k <key-file>] [-u <url>] [-s <server>] [-p <nagios_servers>] -d -h
    Nagios/Icinga check for $description 
    -e <environment>: wallet environment, default is dev 
    -k <key-file>: where to find the json key for the backup bucket
       (default is "/etc/wallet/gcs_wallet_user_serviceaccount.json")
    -u <url> storage url, default is "gs://stage-uit-authnz-wallet-backup/$envird/wallet-db"
    -s <server>: the server in nagios to report this under for passive check (default is hostname -s)
    -p <nagios_servers> Use Nagios passive mode to submit to <nagios_servers>
    -d: Set debug flag on
    -h: this help message
USAGE
}

# getops define them here, and put in usage
while getopts "e:k:u:s:p:dh" OPT; do
    case "$OPT" in
        e) envir="$OPTARG" ;;
        k) keyfile="$OPTARG" ;;
        u) url="$OPTARG" ;;
        s) server="$OPTARG" ;;
        p) nagios_servers="$OPTARG" ;;
        d) debug=true ;;
        h) usage
           exit 3                                     ;;
        *) echo "Unrecognized option: $OPT" >&2
           echo >&2
           usage
           exit 3                                   ;;
    esac
done

## use defaults if we didn't pass in thresholds
if [[ x"$envir" == x"" ]]; then
    envir=$envird
fi

if [[ x"$keyfile" == x"" ]]; then
    keyfile=$keyfiled
fi

# check if the keyfile is actually there
if [ ! -f $keyfile ]; then
    echo >&2
    echo "$keyfile does not exist on this server."
    echo "Please specify an alternate location with -k"
    usage
    exit 3
fi

if [[ x"$url" == x"" ]]; then 
    url="gs://stage-uit-authnz-wallet-backup/$envir/wallet-db"
fi

if [[ x"$nagios_servers" != x"" ]]; then
    passive=1
fi

if [ $passive ] ; then
    if [[ x"$server" == x"" ]]; then
        server=$(hostname -s)
    fi
fi


# test for gcloud/gsutils on the server
cloud=$(gcloud -v | grep -c gsutil )
cloudcode=${?}

if [ $debug ]; then
    echo "cloud is $cloud; code is $cloudcode"
fi

# First, authenticate with GCP
gcloud --no-user-output-enabled auth activate-service-account --key-file=$keyfile

# find out the date (utc) of the latest file
backup=$(gsutil ls -l $url | grep "\.0.tar.gz" )
codebackup=${?}

if [ $debug ]; then
    if [[ x"$backup" == x"" ]] ; then
        echo "no backup found!!"
    fi
    echo "backup is $backup; code is $codebackup"
fi

backupd=$( echo "$backup" | awk '{ print $2 }' )

# convert it into epoch
backupepoch=$(date +%s --date="$backupd")

# get now in utc
nowepoch=$(date +%s)

# calculate seconds
elapsed=$(( nowepoch - backupepoch ))

if [ $debug ]; then
    echo "backupepoch is $backupepoch; now is $nowepoch; elapsed is $elapsed"
fi

# now do the return, order matters here, note the exits
if [[ x"$backup" == x"" ]] ; then
	output="CRITICAL: no backup file found at $url"
    code=2
elif [[ $elapsed -gt $daysec2 ]] ; then
	output="CRITICAL: backup is $elapsed secs old, more than $daysec2"
    code=2
elif [[ $elapsed -gt $daysec ]] ; then
	output="WARNING: backup is $elapsed secs old, more than $daysec"
    code=1
elif [[ $elapsed -le $daysec ]] ; then
    output="OK: backup is $elapsed secs old, less than $daysec"
    code=0
else
	output="UNKNOWN: $itemname doesn't return a valid value for $description, or something else is wrong."
    code=3
fi

if [[ $passive -eq "1" ]] ; then
    if [[ $debug ]]; then
        echo "Submitting passive results"
    fi

    for nagios_server in $(tr ',' ' ' <<< "$nagios_servers")
    do 
        echo "$server~$itemname~$code~$output" | /usr/sbin/send_nsca -d "~" -H $nagios_server
        if [[ $debug ]]; then
            echo "Passive result sent to $nagios_server: $server~$itemname~$code~$output"
        fi
    done
    exit 0
fi

## unless the passives have gone and exited, we get to here
if [[ $debug ]]; then
    echo "Active result sent: $output $code for $server $itemname"
fi

echo "$output"
exit $code

##############################################################################
# Documentation
##############################################################################
DOCS=<<__END_OF_DOCS__
=head1 NAME

```
Usage: ./check_wallet_backups [-e <environment>] [-k <key-file>] [-u <url>] [-s <server>] [-p <nagios_servers>] -d -h
    Nagios/Icinga check for wallet backup test
    -e <environment>: wallet environment, default is dev
    -k <key-file>: where to find the json key for the backup bucket
       (default is "/etc/wallet/gcs_wallet_user_serviceaccount.json")
    -d: Set debug flag on
    -h: this help message


check_wallet_backups --  Check the last wallet backup stored in google cloud storage

=head1 help

check_wallet_backups -h

=head1 DESCRIPTION

This script checks the last wallet backup in GCP and alert if the backup is older than a day (86400 seconds).


=head1 OPTIONS

=over 6

=item environment

wallet environment to check the backup.

=item key-file

 gcs service account key file for the backup bucket; default is "/etc/wallet/gcs_wallet_user_serviceaccount.json"

=item url

 storage url, default is "gs://stage-uit-authnz-wallet-backup/dev/wallet-db"

=item server

 the server in nagios to report this under for passive check (default is hostname -s)

=item nagios_servers

 Use nagios passive mode to submit to <nagios_servers>

=item debug

debug flag on 

=back

=head1 AUTHOR

Linda J Laubenheimer <ljlgeek@stanford.edu>

=cut

##############################################################
##############################################################

__END_OF_DOCS__
