#!/bin/sh

fail() {
    RETVAL="$1"
    MSG="$2"
    echo
    echo -e "ERROR: $MSG"
    exit $RETVAL
}

# Source condor-ce environment
[ -f /usr/share/condor-ce/condor_ce_env_bootstrap ] && . /usr/share/condor-ce/condor_ce_env_bootstrap

# Verify that required dirs are owned by condor:condor (SOFTWARE-2806)
log_dir=$(condor_ce_config_val LOG)
lock_dir=$(condor_ce_config_val LOCK)
required_dirs="${log_dir} ${log_dir}/user ${lock_dir} ${lock_dir}/user"
bad_dirs=$(stat --format "%n %U" $required_dirs | awk '$2 != "condor" {print $0}')
[ -z "$bad_dirs" ] || fail 1 "The following directories are not owned by the condor user:\n$bad_dirs"

# Skip sanity checks if running as a central collector
if [ "$1" != "collector" ]; then
    # Verify configuration using the python bindings
    python3 /usr/share/condor-ce/verify_ce_config.py || exit 6
else
    shift
fi

# Use 'unshare' to allow the HTCondor-CE processes to have a different
# hostname from the rest of the system.

# This allows the HTCondor-CE to function on systems where the default
# system hostname differs from the one used on the public Internet
# (common on dual-networked hosts).

# The hostname is controlled by setting the environment variable
# $CONDORCE_HOSTNAME in /etc/sysconfig/condor-ce.
if [ "X$CONDORCE_HOSTNAME" = "X" ]; then
    exec condor_master "$@"
fi

exec unshare -u -- /usr/share/condor-ce/condor_ce_startup_internal "$@"
