# TODO:
# - https://github.com/jenkinsci/google-git-notes-publisher-plugin
# TODO:
# - https://plugins.jenkins.io/configuration-as-code/
# - https://plugins.jenkins.io/job-dsl/
# - https://plugins.jenkins.io/jobConfigHistory/
plugins="
    blueocean
    pipeline-multibranch-defaults
"

# https://jenkins.io/doc/administration/requirements/java/
sudo apt-get install default-jre-headless

# https://jenkins.io/doc/book/installing/#debianubuntu
# repo_url="https://pkg.jenkins.io/debian/"
repo_url="https://pkg.jenkins.io/debian-stable"
key_url="$repo_url/jenkins.io.key"
sources_file="/etc/apt/sources.list.d/jenkins.list"
# Add key and sources.
wget -q -O - "$key_url" | sudo apt-key add -
sudo sh -c "echo deb $repo_url binary/ > $sources_file"
# Install.
sudo apt-get update
sudo apt-get install jenkins

# https://jenkins.io/doc/book/installing/#setup-wizard
password="$(sudo cat "/var/lib/jenkins/secrets/initialAdminPassword")"
echo "$password"

# Install plugins.
(
    # Change to a temporary working directory.
    tmp_dir="$(mktemp -d)"
    trap 'rm -rf "$tmp_dir"' EXIT
    cd "$tmp_dir"
    # https://jenkins.io/doc/book/managing/cli/#downloading-the-client
    jenkins_cli_url="$JENKINS_URL/jnlpJars/jenkins-cli.jar"
    wget -q "$jenkins_cli_url"
    jenkins_cli="java -jar $(basename "$jenkins_cli_url")"
    # https://jenkins.io/doc/book/managing/cli/#http-connection-mode
    export JENKINS_URL="http://localhost:8080"
    export JENKINS_USER_ID="admin"
    export JENKINS_API_TOKEN="$password"
    # https://jenkins.io/doc/book/managing/plugins/#install-with-cli
    # https://jenkins.io/projects/blueocean/
    $jenkins_cli install-plugin $plugins
)

# Listen only on 127.0.0.0 (localhost) instead of default 0.0.0.0 (all).
sudo sed -i "/etc/default/jenkins" \
    -e 's/^HTTP_PORT=.*/&\n\n# listen address for HTTP connector (default 0.0.0.0)\nHTTP_HOST=127.0.0.1/' \
    -e 's/^\(JENKINS_ARGS="[^"]*--httpPort=[^" ]\+\)\([^"]*"\)$/\1 --httpListenAddress=$HTTP_HOST\2/'

# Restart.
sudo systemctl restart jenkins