#!/bin/bash
# This script sets up the base docker container for use with SDP testing.
# It expects to be run as root within the container.

# Create base directories for use by SDP (see mkdirs.sh)
mkdir /hxdepots
mkdir /hxmetadata1
mkdir /hxmetadata2
mkdir /hxlogs

# Create Perforce group and user within that group, and allow them sudo privileges
groupadd perforce
useradd -d /p4 -s /bin/bash -m perforce -g perforce
echo 'perforce ALL=(ALL) NOPASSWD:ALL'> /tmp/perforce
chmod 0440 /tmp/perforce
chown root:root /tmp/perforce
mv /tmp/perforce /etc/sudoers.d
echo perforce:Password | chpasswd

#
# Helpful profile for perforce user login profile - for manual testing mainly
#
BASH_PROF=/p4/.bash_profile
cat <<"EOF" >$BASH_PROF
export PATH=/sdp/Server/Unix/p4/common/bin:$PATH
export P4CONFIG=.p4config
export P4P4PORT=1666
PS1='\u@\h:\w$ '
EOF
chown perforce:perforce $BASH_PROF

#
# Script to reset SDP for tests in case of multiple runs.
#
RESET_SDP=/p4/reset_sdp.sh
cat <<"EOF" >$RESET_SDP
#!/bin/bash
sudo cp -R /sdp /hxdepots
sudo chown -R perforce:perforce /hxdepots/sdp
EOF
chmod +x $RESET_SDP
chown perforce:perforce $RESET_SDP

#
# Script to run SDP tests - run by Docker entry script below (or can be run
# manually).
#
RUN_SDP_TESTS=/p4/test_sdp.sh
cat <<"EOF" >$RUN_SDP_TESTS
#!/bin/bash
/p4/reset_sdp.sh
ln -s /sdp/Server/test/test_SDP.py /p4/test_SDP.py
python3 /p4/test_SDP.py
result=$?
[[ $result -eq 0 ]] || tail /tmp/SDPTest.log
exit $result
EOF
chmod +x $RUN_SDP_TESTS
chown perforce:perforce $RUN_SDP_TESTS

#
# Script to run mkrep tests
#
RUN_MKREP_TESTS=/p4/test_mkrep.sh
cat <<"EOF" >$RUN_MKREP_TESTS
#!/bin/bash
/p4/reset_sdp.sh
ln -s /sdp/Server/test/test_SDP.py /p4/test_SDP.py
python3 /p4/test_SDP.py --instance 1 --setup
result=$?
[[ $result -eq 0 ]] || tail /tmp/SDPTest.log
cp /sdp/Server/Unix/p4/common/config/SiteTags.cfg /p4/common/config/
/p4/common/bin/mkrep.sh -i 1 -t ha -s bos -r replica1
exit $result
EOF
chmod +x $RUN_MKREP_TESTS
chown perforce:perforce $RUN_MKREP_TESTS

#
# The file run by docker for basic tests - just runs the above script as perforce user
# Note that the output file is collected by script run_docker_tests.sh
#
DOCKER_ENTRY=/p4/docker_entry.sh
cat <<"EOF" >$DOCKER_ENTRY
#!/bin/bash
su -l perforce -c /p4/test_sdp.sh > /sdp/test/output/test-${TESTOS}.out 2>&1
EOF
chmod +x $DOCKER_ENTRY
chown perforce:perforce $DOCKER_ENTRY
