#!/bin/bash

# Running on 2.555.1 with Echarts 6.0.0-1281.vd3d21a_1ca_cb_4 causes the 'Elastic Search' indexer to disappear
# Upgrade to 2.555.1 and upgrade all plugins will fail to restart with console stack traces
#
# https://issues.jenkins.io/browse/JENKINS-76444

set -euxo pipefail

JENKINS_WAR_VERSION=2.541.3
PLUGIN_MANAGER_VERSION=2.14.0

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

DEBUG="-agentlib:jdwp=transport=dt_socket,server=y,address=8000,suspend=n"
SKIP_SETUP="-Djenkins.install.runSetupWizard=false"
JENKINS_HOME=. java ${DEBUG} ${SKIP_SETUP} -jar ${CACHE_DIR}/jenkins.war
