ARG JENKINS_VERSION=2.555.3

FROM jenkins/jenkins:${JENKINS_VERSION}-lts-slim AS base

USER root

# Run updates
RUN apt-get -y update \
  && apt-get -y upgrade \
  && apt-get -y clean \
  && rm -rf /var/lib/apt/lists/*

USER jenkins

# Skip installation wizard
RUN echo 2.0 > /usr/share/jenkins/ref/jenkins.install.UpgradeWizard.state

############################
### Lock plugin versions ###
############################

FROM base AS lock-plugins

COPY plugins.txt /usr/share/jenkins/ref/plugins.txt
COPY lock-plugins.sh /usr/share/jenkins/ref/lock-plugins.sh
ENTRYPOINT ["/usr/share/jenkins/ref/lock-plugins.sh"]
CMD ["/usr/share/jenkins/ref/plugins.txt", "/usr/share/jenkins/ref/output/plugins-lock.txt"]

##############################
### Build image for deploy ###
##############################

FROM base AS deploy

# Install plugins
COPY plugins-lock.txt /usr/share/jenkins/ref/plugins-lock.txt
RUN jenkins-plugin-cli -f /usr/share/jenkins/ref/plugins-lock.txt --verbose

# Add GitHub to SSH known hosts
RUN mkdir -p ~/.ssh
RUN ssh-keyscan github.com >> ~/.ssh/known_hosts

# Define a separate volume for plugins directory. This is required in addition to defining it
# as a volume in the deployment configuration, to ensure that the Jenkins user has permissions
RUN mkdir -p /var/jenkins_home/plugins
VOLUME ["/var/jenkins_home/plugins"]
