#!/bin/bash
set -e

function create_user()
{
  local name="$1"
  local full_name="$2"
  local id="$3"
  create_group $name $id
  if ! grep -q "^$name:" /etc/passwd; then
    sudo adduser --uid $id --gid $id --disabled-password --gecos "$full_name" $name
  fi
  sudo usermod -L $name
}

function create_group()
{
  local name="$1"
  local id="$2"
  if ! grep -q "^$name:" /etc/group >/dev/null; then
    sudo addgroup --gid $id $name
  fi
}

set -x

wget -q -O - http://pkg.jenkins-ci.org/debian/jenkins-ci.org.key | sudo apt-key add -
echo deb http://pkg.jenkins-ci.org/debian binary/ | sudo tee /etc/apt/sources.list.d/jenkins.list
sudo apt-get update
sudo apt-get install -y jenkins acl git ca-certificates ruby
sudo usermod -a -G passenger_ci,docker jenkins
if [[ -e /vagrant ]]; then
  sudo service jenkins stop
  sudo update-rc.d -f jenkins disable
  if [[ ! -e /srv/passenger_rpm_automation ]]; then
    sudo ln -s /vagrant /srv/passenger_rpm_automation
  fi
fi

create_user psg_rpm_automation "Passenger RPM automation" 2466

create_group passenger_ci 2450
sudo usermod -a -G passenger_ci,docker psg_rpm_automation
sudo mkdir -p /var/cache/passenger_ci
sudo touch /var/cache/passenger_ci/lock
sudo chown -R root:passenger_ci /var/cache/passenger_ci
sudo chmod 770 /var/cache/passenger_ci
sudo chmod 660 /var/cache/passenger_ci/lock

sudo mkdir -p /etc/passenger_rpm_automation
sudo touch /etc/passenger_rpm_automation/signing_passphrase
sudo chown jenkins: /etc/passenger_rpm_automation/signing_passphrase
sudo chmod 600 /etc/passenger_rpm_automation/signing_passphrase
if [[ ! -e signing_passphrase ]]; then
  sudo ln -s /etc/passenger_rpm_automation/signing_passphrase signing_passphrase
fi

if [[ ! -e /tools ]]; then
  sudo git clone https://github.com/phusion/phusion-server-tools.git /tools
fi
