#! /bin/bash

set -e

# Copy files from /usr/share/jenkins/ref into /var/jenkins_home
# So the initial JENKINS-HOME is set with expected content. 
# Don't override, as this is just a reference setup, and use from UI 
# can then change this, upgrade plugins, etc.
copy_reference_file() {
	f=${1%/} 
	echo "$f" >> $COPY_REFERENCE_FILE_LOG
    rel=${f:23}
    dir=$(dirname ${f})
    echo " $f -> $rel" >> $COPY_REFERENCE_FILE_LOG
	if [[ ! -e /var/jenkins_home/${rel} ]] 
	then
		echo "copy $rel to JENKINS_HOME" >> $COPY_REFERENCE_FILE_LOG
		mkdir -p /var/jenkins_home/${dir:23}
		cp -r /usr/share/jenkins/ref/${rel} /var/jenkins_home/${rel};
		# pin plugins on initial copy
		[[ ${rel} == plugins/*.jpi ]] && touch /var/jenkins_home/${rel}.pinned
	fi; 
}
export -f copy_reference_file
echo "--- Copying files at $(date)" >> $COPY_REFERENCE_FILE_LOG
find /usr/share/jenkins/ref/ -type f -exec bash -c "copy_reference_file '{}'" \;

#echo "--- Setting locations ---"
#MYLOC=`cat /myfiles/jenkinslocation.txt` 
#echo "Jenkins Location: $MYLOC"
#sed -i "s/<jenkinsUrl>.*<\/jenkinsUrl>/<jenkinsUrl>http:\/\/$MYLOC\/<\/jenkinsUrl>/g" /var/jenkins_home/jenkins.model.JenkinsLocationConfiguration.xml
#sed -i "s/<serverUrl>.*<\/serverUrl>/<serverUrl>tcp:\/\/$MYLOC:3375\/<\/serverUrl>/g" /var/jenkins_home/config.xml
#sed -i "s/envVars.put(\"DOCKER_HOST\", \".*\")/envVars.put(\"DOCKER_HOST\", \"tcp:\/\/$MYLOC:3375\")/g" /var/jenkins_home/init.groovy.d/global-env.groovy
#sed -i "s/<baseUrl>.*<\/baseUrl>/<baseUrl>http:\/\/$MYLOC\/<\/baseUrl>/g" /var/jenkins_home/jenkins.plugins.slack.SlackNotifier.xml 

# if `docker run` first argument start with `--` the user is passing jenkins launcher arguments
if [[ $# -lt 1 ]] || [[ "$1" == "--"* ]]; then
   exec java $JAVA_OPTS -Djenkins.install.runSetupWizard=false -jar /usr/share/jenkins/jenkins.war $JENKINS_OPTS "$@"
fi

# As argument is not jenkins, assume user want to run his own process, for sample a `bash` shell to explore this image
exec "$@"
