#!/bin/bash
export SDP_INSTANCE=${SDP_INSTANCE:-Unset}
export SDP_INSTANCE=${1:-$SDP_INSTANCE}
if [[ $SDP_INSTANCE == Unset ]]; then
   echo -e "\nError: Instance parameter not supplied.\n"
   echo "You must supply the Perforce instance as a parameter to this script."
   exit 1
fi

# Load SDP controlled shell environment.
source /p4/common/bin/p4_vars "$SDP_INSTANCE" ||\
   { echo -e "\nError: Failed to load SDP environment.\n"; exit 1; }

source $P4CBIN/backup_functions.sh ||\
   { echo -e "\nError: Failed to load SDP backup_functions.sh lib.\n"; exit 1; }

cd $P4CBIN || { echo -e "\nError: Failed to cd to $P4CBIN.\n"; exit 1; }
common_dir=$(pwd -P)

if [[ -d $common_dir ]]; then
  cd $common_dir || { echo -e "\nError: Failed to cd to $common_dir.\n"; exit 1; }
else
  echo $common_dir does not exist.
  exit 1
fi

######### Start of Script ##########

check_vars
set_vars

export LOGFILE=$LOGS/upgrade.$P4SERVER.log.$(date +'%Y%m%d-%H%M')


check_dirs
check_uid

[[ -f $common_dir/p4 ]] || { echo "No p4 in $common_dir" ; exit 1 ;}
[[ -f $common_dir/p4d ]] || { echo "No p4d in $common_dir" ; exit 1 ;}

chmod 755 $common_dir/p4
chmod 700 $common_dir/p4d
[[ -f $common_dir/p4broker ]] && chmod 700 $common_dir/p4broker
[[ -f $common_dir/p4p ]] && chmod 700 $common_dir/p4p

$P4CBIN/p4login -v >> $LOGFILE 2>&1
if [[ -x /p4/${SDP_INSTANCE}/bin/p4d_${SDP_INSTANCE}_init ]]; then
   if [[ "$P4REPLICA" == "FALSE" ]] || [[ $EDGESERVER -eq 1 ]]; then
      get_journalnum
   fi
   stop_p4d
fi

cd /p4/common/bin/

NEW_P4RELNUM=$(./p4 -V | grep -i Rev. | $AWK -F / '{print $3}')
NEW_P4DRELNUM=$(./p4d -V | grep -i Rev. | $AWK -F / '{print $3}')
NEW_P4BLDNUM=$(./p4 -V | grep -i Rev. | $AWK -F / '{print $4}' | awk '{print $1}')
NEW_P4DBLDNUM=$(./p4d -V | grep -i Rev. | $AWK -F / '{print $4}' | awk '{print $1}')
NEW_P4DRELEASE=$(./p4d -V | grep -i Rev. | $AWK '{print $2}')

log "Start $P4SERVER Upgrade on $(hostname)."
log "New server release: $NEW_P4DRELEASE"

cd /p4/${SDP_INSTANCE}/bin/
rm -f p4*_20* > /dev/null 2>&1
rm -f p4_${SDP_INSTANCE} > /dev/null 2>&1
rm -f p4d_${SDP_INSTANCE}_bin > /dev/null 2>&1
[[ -f p4_$NEW_P4RELNUM.$NEW_P4BLDNUM ]] || cp $common_dir/p4 p4_$NEW_P4RELNUM.$NEW_P4BLDNUM
[[ -f p4d_$NEW_P4DRELNUM.$NEW_P4DBLDNUM ]] || cp $common_dir/p4d p4d_$NEW_P4DRELNUM.$NEW_P4DBLDNUM
ln -s p4d_$NEW_P4DRELNUM.$NEW_P4DBLDNUM p4d_${SDP_INSTANCE}_bin >> "$LOGFILE" 2>&1
ln -s p4_$NEW_P4RELNUM.$NEW_P4BLDNUM p4_${SDP_INSTANCE} >> "$LOGFILE" 2>&1

# Create broker links if broker exists
if [[ -f /p4/common/bin/p4broker ]]; then
   if [[ -x /p4/${SDP_INSTANCE}/bin/p4broker_${SDP_INSTANCE}_init && \
         -f /p4/common/config/p4_${SDP_INSTANCE}.broker.cfg ]]; then
      stop_p4broker
   fi
   P4BRELNUM=`/p4/common/bin/p4broker -V | grep -i Rev. | $AWK -F / '{print $3}'`
   P4BBLDNUM=`/p4/common/bin/p4broker -V | grep -i Rev. | $AWK -F / '{print $4}' | $AWK '{print $1}'`
   cp /p4/common/bin/p4broker /p4/${SDP_INSTANCE}/bin/p4broker_$P4BRELNUM.$P4BBLDNUM
   [[ -L p4broker_${SDP_INSTANCE} ]] && unlink p4broker_${SDP_INSTANCE}
   ln -s p4broker_$P4BRELNUM.$P4BBLDNUM p4broker_${SDP_INSTANCE}
   sed "s/REPL_SDP_INSTANCE/${SDP_INSTANCE}/g" /p4/common/etc/init.d/p4broker_instance_init.template > p4broker_${SDP_INSTANCE}_init
   chmod +x p4broker_${SDP_INSTANCE}_init
   if [[ -x /p4/${SDP_INSTANCE}/bin/p4broker_${SDP_INSTANCE}_init && \
         -f /p4/common/config/p4_${SDP_INSTANCE}.broker.cfg ]]; then
      start_p4broker
   fi
fi

# Create p4p links if p4p exists
if [[ -x /p4/common/bin/p4p ]]; then
   if [[ -x /p4/${SDP_INSTANCE}/bin/p4p_${SDP_INSTANCE}_init ]]; then
      stop_p4p
   fi
   P4PRELNUM=`/p4/common/bin/p4p -V | grep -i Rev. | $AWK -F / '{print $3}'`
   P4PBLDNUM=`/p4/common/bin/p4p -V | grep -i Rev. | $AWK -F / '{print $4}' | $AWK '{print $1}'`
   cp /p4/common/bin/p4p /p4/${SDP_INSTANCE}/bin/p4p_$P4PRELNUM.$P4PBLDNUM
   [[ -L p4p_${SDP_INSTANCE} ]] && unlink p4p_${SDP_INSTANCE}
   ln -s p4p_$P4PRELNUM.$P4PBLDNUM p4p_${SDP_INSTANCE}
   sed -e "s/REPL_SDP_INSTANCE/${SDP_INSTANCE}/g" \
     -e "s/REPL_DNSNAME/${P4DNSNAME}/g" \
     /p4/common/etc/init.d/p4p_instance_init.template > p4p_${SDP_INSTANCE}_init
   chmod +x p4p_${SDP_INSTANCE}_init
   if [[ -x /p4/${SDP_INSTANCE}/bin/p4p_${SDP_INSTANCE}_init ]]; then
      start_p4p
   fi
fi

# Only rotate the journal on the master.
if [[ "$P4REPLICA" == "FALSE" ]] && [[ $EDGESERVER -eq 0 ]]; then
  log "Processing. This may take a few minutes depending on time to rotate the active journal and replay to the offline_db."
  p4d_truncate_journal
  get_journalnum
  get_offline_journal_num
  replay_journals_to_offline_db
fi

log "Upgrading databases in $P4ROOT."
# For versions >= 19.1 we should journal the upgrade and not upgrade offline
# In such cases we let offline_db be upgraded by applying rotate journals in the
# normal way.
UPGRADE_JNL="$P4JOURNAL"
if [[ "${NEW_P4DRELNUM}.${NEW_P4DBLDNUM}" < "18.2" ]]; then
  UPGRADE_JNL=off
fi
$P4DBIN -r $P4ROOT -J $UPGRADE_JNL -xu >> "$LOGFILE" 2>&1 || die "Failed to upgrade root database"
# Upgrade the offline database on the master and on edge servers.
if [[ "$P4REPLICA" == "FALSE" ]] || [[ $EDGESERVER -eq 1 ]]; then
  if [[ "$UPGRADE_JNL" == "off" ]]; then
    log "Upgrading databases in $OFFLINE_DB as this is a pre 18.2 server upgrade"
    # The value of '-t localhost:0000' is necessary for syntax reasons;
    # it is ignored. This allows upgade of offline databases without needing
    # a license file; there isn't one in offline_db, only P4ROOT.  A valid
    # license file is required to actually start the server process and have
    # it listen on a port.
    $P4DBIN -r $OFFLINE_DB -J $UPGRADE_JNL -xu -t localhost:0000 >> "$LOGFILE" 2>&1 || die "Failed to upgrade offline_db"
  else
    if [[ "$P4REPLICA" == "FALSE" ]] && [[ $EDGESERVER -eq 0 ]]; then
      log "Upgrade offline through rotating latest journal on master/commit server"
      p4d_truncate_journal
      get_journalnum
      get_offline_journal_num
      replay_journals_to_offline_db
    fi
  fi
fi

if [[ "${NEW_P4DRELNUM}.${NEW_P4DBLDNUM}" > "19.1" ]]; then
  if [[ -x /p4/${SDP_INSTANCE}/bin/p4d_${SDP_INSTANCE}_init ]]; then
     start_p4d
  fi

  if [[ "$P4REPLICA" == "FALSE" && $EDGESERVER -eq 0 ]]; then
     log "Upgrading protections table comment format."
     $P4BIN protect --convert-p4admin-comments -o | $P4BIN protect -i
  fi
fi

log "Finished $P4SERVER Upgrade"
cat $LOGFILE
