#!/bin/bash

MAX_ATTEMPTS=3
ATTEMPT=1
SUCCESS=0

if ! which kinit > /dev/null 2>&1; then
    echo "Program 'kinit' not found. Please install Kerberos package."
    exit 1
fi

echo "Kerberos Authentication:"

while [ $ATTEMPT -le $MAX_ATTEMPTS ]; do
    echo -n "Attempt ($ATTEMPT/$MAX_ATTEMPTS): "

    ISTIMEOUT=0
    TIMEOUT_DURATION=$((3 * 60 * 60))  # 3 hours
    if timeout --foreground $TIMEOUT_DURATION kinit $@; then
        SUCCESS=1
        break
    else
		ISTIMEOUT=$?
        ((ATTEMPT++))
        if [ $ATTEMPT -le $MAX_ATTEMPTS ]; then
            echo "Authentication failed. Please try again."
        fi
    fi
    if [ $ISTIMEOUT -eq 124 ]; then
		echo "Authentication failed. The timeout is up."
		break;
    fi
done

if [ $SUCCESS -eq 0 ] && [ ! $ISTIMEOUT -eq 124 ]; then
    echo "Authentication failed. Maximum attempts reached."
    exit 1
fi
