#!/bin/bash

port=1666
script_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
root_dir="$script_dir/trn_p4root"
logs_dir="$root_dir/logs"
checkpoints_dir="$root_dir/checkpoints"

echo "$script_dir"

#------------------------------------------------------------------------------
# If exes are not already here, try to find them on the path.
for exe in p4 p4d p4broker; do
   if [[ ! -x ./$exe ]]; then
      if [[ -n "$(which $exe)" ]]; then
         echo Using $exe found on path.
         cp "$(which $exe)" .
      else
         if [[ $exe != p4broker ]]; then
            echo "Error: Missing executable file $exe"
         fi
      fi
   fi
done

p4="$script_dir/p4"
p4d="$script_dir/p4d"
p4broker="$script_dir/p4broker"

if [[ -d "$root_dir" ]]; then
   echo "Cleaning up from earlier install."
   $p4 -p $port -u bruno admin stop > /dev/null 2>&1
   sleep 1
   rm -rf "$root_dir"
fi

echo "Installing sample data with P4ROOT=$root_dir."
mkdir "$root_dir"
mkdir "$logs_dir"
mkdir "$checkpoints_dir"
if [[ "$(uname)" == Darwin ]]; then
   $p4d -r "$root_dir" -jr "$script_dir/checkpoint.mac"
else
   $p4d -r "$root_dir" -jr "$script_dir/checkpoint.linux"
fi

$p4d -r "$root_dir" -xu

echo "Starting server"
if [[ "$(uname)" == Darwin ]]; then
   $p4d -r "$root_dir" -p $port -J "$logs_dir/journal" -L "$logs_dir/log" -q -d
else
   $p4d -C0 -r "$root_dir" -p $port -J "$logs_dir/journal" -L "$logs_dir/log" -q -d
fi

sleep 1

echo "Configuring server"
$p4 -p $port -u bruno configure set server.depot.root="$script_dir/depots"
$p4 -p $port -u bruno configure set journalPrefix="$checkpoints_dir/p4_1"
$p4 -p $port -u bruno -c bruno_ws client -o | sed "s#REPME#$HOME#" | $p4 -p $port -u bruno client -i

if [[ -x $p4broker ]]; then
   $p4broker -C > p4broker.cfg
fi

if [[ -r p4v.tgz ]]; then
    tar -xvzf p4v.tgz
elif [[ -r P4V.dmg ]]; then
    open P4V.dmg
else
    echo "Install P4V from: https://www.perforce.com/downloads/helix-visual-client-p4v"
fi

echo Run "source $script_dir/p4vars" to set up your environment.
echo Run "$script_dir/uninstall.sh" to remove the training environment.
