#!/bin/bash

#replace with latest

KERNEL=4.4.68-33

#E.g. porto-kernel-4.4-stable-01
AGENTNAME=`hostname`

#Waiting for the net setup

while ! ping6 -c 1 search-precise.dist.yandex.ru; do sleep 1; done

#Update sources lists

echo -e "deb http://search-kernel.dist.yandex.ru/search-kernel/ stable/amd64/\ndeb http://search-kernel.dist.yandex.ru/search-kernel/ unstable/amd64/\ndeb http://search-kernel.dist.yandex.ru/search-kernel/ stable/all/\ndeb http://search-kernel.dist.yandex.ru/search-kernel/ unstable/all/" | tee /etc/apt/sources.list.d/search-kernel.list

echo -e "deb http://search-precise.dist.yandex.ru/search-precise unstable/amd64/\ndeb http://search-precise.dist.yandex.ru/search-precise unstable/all/\ndeb http://search-precise.dist.yandex.ru/search-precise stable/amd64/\ndeb http://search-precise.dist.yandex.ru/search-precise stable/all/" | tee /etc/apt/sources.list.d/portod.list

apt-get update

#Install kernel

apt-get install -y linux-image-$KERNEL

#Install packages

apt-get install -y teamcity-agent unzip cmake debhelper pkg-config autoconf libtool protobuf-compiler libprotobuf-dev libncurses5-dev libnl-3-dev libnl-route-3-dev bison flex g++-4.7 dh-python python-all python-setuptools bash-completion libssl-dev python-protobuf python-psutil vmtouch/unstable stress python-dev python-pip yandex-coverity

pip install --upgrade psutil

#Prepare porto src checkout dir

mkdir -p /place/src/porto
chown -R teamcity:dpt_virtual_robots /place/src

#Import layers

wget  http://sandbox147.search.yandex.net:13578/4/1/122102414/ubuntu-precise.tgz

apt-get install -y yandex-porto
portoctl layer -I ubuntu-precise ./ubuntu-precise.tgz
apt-get purge -y yandex-porto

#Prepare uids

for g in porto porto-containers ; do
	getent group $g || groupadd $g
done

for u in porto-alice porto-bob; do
	id $u || useradd $u -G porto
	getent group ${u}-containers || groupadd ${u}-containers
done

id porto-charlie || useradd porto-charlie -G porto-containers
id porto-david || useradd porto-david -G porto-alice-containers

#Install agent

/etc/init.d/teamcity-agent install $AGENTNAME http://teamcity.yandex-team.ru teamcity

#Manual steps required

echo "#"`id -u teamcity`"   ALL=(ALL:ALL) NOPASSWD: ALL" | tee /etc/sudoers.d/teamcity
chmod 0440 /etc/sudoers.d/teamcity

#Startup scripts

cat <<EOF > /etc/init/porto-teamcity.conf
# porto-teamcity

description "porto-teamcity"

start on runlevel [2345]
stop on runlevel [!2345]

respawn

script
	sleep 5
	/etc/init.d/teamcity-agent start $AGENTNAME
end script
EOF

reboot
