#!/bin/bash
set -u
declare ThisScript=${0##*/}
declare Version=1.0.2
# Sample Test Usage:
# login_if_needed.sh public.perforce.com:1666 tom_tyler /Users/ttyler/pub/.p4passwd
# This sample script is intended to illustrate logic that can be used to avoid
# unnecessary logins to a Perforce Helix Core server. A 'p4 login -s' is used
# with tagged output (enabled with '-ztag') to extract the number of seconds
# remaining on the current ticket, the TicketExpiration field in the output of
# p4 login -s. If that value is "long enough" (31 days in this example), then
# the current ticket is deemed good enough, and no login is done. If the
# duration is too short, the user isn't logged in at all, a login will be
# attempted using a password file.
# Test values.
declare P4PORT=${1:-perforce:1666}
declare P4USER=${2:-UnknownUser}
declare PasswordFile=${3:-/path/to/your/.p4passwd}
declare -i ErrorCount=0
declare -i Debug=${DEBUG:-0}
# A 'long-term' ticket is one that expires more than a month (31 days + 1 second) from now.
# This is represented as seconds, 2678401. Use a smaller value for debugging.
### declare -i LongTermTicketExpiration=2678401
declare -i LongTermTicketExpiration=600
#------------------------------------------------------------------------------
# Micro-functions.
function msg () { echo -e "$*"; }
function dbg () { [[ "$Debug" -eq 0 ]] || msg "DEBUG: $*"; }
function errmsg () { msg "\\nError: ${1:-Unknown Error}"; ErrorCount+=1; }
function bail () { errmsg "${1:-Unknown Error}"; exit "$ErrorCount"; }
#------------------------------------------------------------------------------
# Function: login_if_needed ($port, $user, $passwordFile)
function login_if_needed() {
local port=${1:-}
local user=${2:-}
local pFile=${3:-}
local ticketExpiration=
local cmd=
ticketExpiration=$(p4 -ztag -F %TicketExpiration% -p "$port" -u "$user" login -s 2>/dev/null)
cmd="p4 -p $port -u $user -s login -a"
if [[ "$ticketExpiration" =~ [0-9]+ ]]; then
if [[ "$ticketExpiration" -ge "$LongTermTicketExpiration" ]]; then
msg "User $user already logged into $port with a long-term ticket. Login not required."
return 0
else
msg "Warning: User $user logged into $port with a short-term ticket. Attempting to extend."
dbg "Running: $cmd"
$cmd < "$pFile" || return 1
fi
else
msg "User $user is not logged into $port. Attempting to login."
dbg "Running: $cmd"
$cmd < "$pFile" || return 1
fi
return 0
}
#------------------------------------------------------------------------------
# Main Program
msg "Starting $ThisScript v$Version as $USER@${HOSTNAME%%.*}"
login_if_needed "$P4PORT" "$P4USER" "$PasswordFile"