#!/bin/bash

set -e

# Get the number of seconds since the password was changed for
# principal supplied at the command line.

PRINCIPAL=$1

USAGE="kdc-get-last-pwchange principal-name"

if [[ -z "$PRINCIPAL" ]]; then
  echo $USAGE
  exit 0
fi

export PATH="/usr/sbin:/usr/bin:/bin"
DATE_CHANGED=`kadmin -l get --column-info=last_pwd_change ${PRINCIPAL}`

# DATE_CHANGED has the format:
#    Last password change: 2017-05-03 21:39:35 UTC
#
# Extract the date.
DATE_RX="([0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2}.*)"
if [[ $DATE_CHANGED =~ $DATE_RX ]]; then
  DATE="${BASH_REMATCH[1]}"

  # Convert to epoch time
  PW_EPOCH="$(date --date "$DATE" +%s)"

  # Get the current epoch time
  CURRENT_EPOCH="$(date +%s)"

  DIFF_SECS=`expr $CURRENT_EPOCH - $PW_EPOCH`
  if ((DIFF_SECS < 0)); then
    echo "last password change time is in the future?!?"
    exit 88
  else
    echo $DIFF_SECS
    exit 0
  fi
else
  echo "problem parsing $DATE_CHANGED"
  exit 99
fi

# Documentation.  Use a hack to hide this from the shell.  Because of the
# above exit line, this should never be executed.
DOCS=<<__END_OF_DOCS__

=head1 NAME

kdc-get-last-pwchange - Get last password change time of test principal

=head1 SYNOPSIS

B<kdc-get-last-pwchange>

=head1 DESCRIPTION

Returns the number of seconds since the last password change of the the
Kerberos principal of C<testing/replication> and exits with return value
of 0. If the number of seconds is negative, exits with return value 88.

=head1 AUTHOR

Adam Lewenberg <adamhl@stanford.edu>

=cut

__END_OF_DOCS__
