#!/bin/bash

# https://issues.jenkins.io/browse/JENKINS-48363
#
# CSRF protection prevents clone from Jenkins userContent.git

set -euxo pipefail

JENKINS_WAR_VERSION=2.568.2
PLUGIN_MANAGER_VERSION=2.15.0

if [ ! -d userContent/.git ]; then
  mkdir -p userContent
  pushd userContent
  git init --initial-branch=master
  git config --local commit.gpgsign false
  echo 'Sample repository in userContent directory' > README
  git add README
  git commit -m "Add README" README
  popd # userContent
fi

curl_cmd="curl --fail --silent --show-error --location"

# Create cache directory for plugin manager jar
PLUGIN_CACHE_DIR=../.cache/${PLUGIN_MANAGER_VERSION}
[ -d ${PLUGIN_CACHE_DIR} ] || mkdir -p ${PLUGIN_CACHE_DIR}

# Download plugins defined in plugins.txt
[ -d plugins ] || mkdir plugins
PLUGIN_MANAGER_JAR=jenkins-plugin-manager-${PLUGIN_MANAGER_VERSION}.jar
PLUGIN_MANAGER_URL=https://github.com/jenkinsci/plugin-installation-manager-tool/releases/download
CACHED_PLUGIN_MANAGER_JAR=${PLUGIN_CACHE_DIR}/$PLUGIN_MANAGER_JAR
[ -f ${CACHED_PLUGIN_MANAGER_JAR} ] || $curl_cmd --output ${CACHED_PLUGIN_MANAGER_JAR} ${PLUGIN_MANAGER_URL}/${PLUGIN_MANAGER_VERSION}/$PLUGIN_MANAGER_JAR
java -jar ${CACHED_PLUGIN_MANAGER_JAR} --jenkins-version $JENKINS_WAR_VERSION --latest false --plugin-download-directory plugins --plugin-file plugins.txt

# Create the cache directory
CACHE_DIR=../.cache/${JENKINS_WAR_VERSION}
[ -d ${CACHE_DIR} ] || mkdir -p ${CACHE_DIR}

# Download Jenkins war file
[[ ${JENKINS_WAR_VERSION} == *.*.* ]] && JENKINS_WAR_DIR=war-stable || JENKINS_WAR_DIR=war
JENKINS_DOWNLOAD_URL=https://get.jenkins.io/${JENKINS_WAR_DIR}/${JENKINS_WAR_VERSION}
CACHED_WAR=${CACHE_DIR}/jenkins.war
[ -f ${CACHED_WAR} ]        || $curl_cmd --output ${CACHED_WAR}        ${JENKINS_DOWNLOAD_URL}/jenkins.war
[ -f ${CACHED_WAR}.asc ]    || $curl_cmd --output ${CACHED_WAR}.asc    ${JENKINS_DOWNLOAD_URL}/jenkins.war.asc
[ -f ${CACHED_WAR}.sha256 ] || $curl_cmd --output ${CACHED_WAR}.sha256 ${JENKINS_DOWNLOAD_URL}/jenkins.war.sha256
gpg --verify --quiet --trust-model direct --quiet ${CACHED_WAR}.asc    ${CACHED_WAR}
pushd ${CACHE_DIR}
sha256sum --check --status jenkins.war.sha256
popd

# Let CasC configure the Jenkins URL
h=$(hostname)
[[ $h == *.* ]] && HOSTNAME=$h || HOSTNAME=$h.$(dnsdomainname)
export HOSTNAME

JAVA_HOME=/opt/jdk-25
PATH=${JAVA_HOME}/bin:$PATH
SKIP_SETUP="-Djenkins.install.runSetupWizard=false"
DISABLE_CSRF="-Dhudson.security.csrf.GlobalCrumbIssuerConfiguration.DISABLE_CSRF_PROTECTION=true"
JENKINS_HOME=. java ${SKIP_SETUP} ${DISABLE_CSRF} -jar ${CACHE_DIR}/jenkins.war
