#!/usr/bin/env bash

# Исходник этого кода - в репозитории https://github.yandex-team.ru/tools/tools-trendbox
# Версия: 0.2.2

set -ex

DEBIAN_FRONTEND=noninteractive apt-get install curl ca-certificates apt-transport-https lsb-release git software-properties-common dnsmasq -y -qq

# ---------------------------------------------------------------

# Нужно добавить в LXC /etc/trendbox файл. Он будет вызываться при старте trendbox job'ы.
echo > /etc/trendbox

# ---------------------------------------------------------------

# Репозиторий для yandex-internal-root-ca
cat <<EOF > /etc/apt/sources.list.d/dist.list
deb http://dist.yandex.ru/common stable/all/
EOF

# ---------------------------------------------------------------

mkdir -p /etc/docker/
cat <<EOF > /etc/docker/daemon.json
{
    "debug": true,
    "storage-driver": "overlay2",
    "ipv6": true,
    "iptables": false,
    "ip-forward": false,
    "dns": ["172.17.0.1"],
    "fixed-cidr-v6": "fd00::/8"
}
EOF

# ---------------------------------------------------------------

cat <<EOF > /etc/resolv.conf.local
search search.yandex.net yandex.ru
# https://st.yandex-team.ru/FEI-9087#1518603403000
nameserver 127.0.0.1
# ns64-cache.yandex.net
nameserver 2a02:6b8:0:3400::5005
EOF

# ---------------------------------------------------------------

curl -fsSL http://dist.yandex.ru/yandexrepo/GPG-KEY-yandex | apt-key add -
curl -fsSL https://download.docker.com/linux/ubuntu/gpg | apt-key add -
add-apt-repository "deb [arch=amd64] https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable"

DEBIAN_FRONTEND=noninteractive apt-get update -qq
DEBIAN_FRONTEND=noninteractive apt-get install -y -qq --no-upgrade --no-install-recommends yandex-internal-root-ca python-setuptools python-virtualenv python-pip python3-pip python3-venv python3-setuptools tinyproxy plzip make

DEBIAN_FRONTEND=noninteractive apt-get install -y docker-ce=17.09.1~ce-0~ubuntu

# Включает автозапуск сервисов в systemd
systemctl enable docker
systemctl enable dnsmasq

curl -L https://github.com/docker/compose/releases/download/1.21.2/docker-compose-$(uname -s)-$(uname -m) -o /usr/local/bin/docker-compose
chmod +x /usr/local/bin/docker-compose

# ---------------------------------------------------------------

pip install -i https://pypi.yandex-team.ru/simple/ click==6.6 releaser-cli[all]==0.49

# ---------------------------------------------------------------

cat <<EOF > /etc/tinyproxy.conf
User nobody
Group nogroup
Port 8888
Timeout 600
DefaultErrorFile "/usr/share/tinyproxy/default.html"
StatFile "/usr/share/tinyproxy/stats.html"
Logfile "/var/log/tinyproxy/tinyproxy.log"
LogLevel Error
PidFile "/var/run/tinyproxy/tinyproxy.pid"
MaxClients 100
MinSpareServers 5
MaxSpareServers 20
StartServers 10
MaxRequestsPerChild 0
Allow 0.0.0.0/0
ViaProxyName "tinyproxy"
ConnectPort 443
ConnectPort 563
EOF

# ---------------------------------------------------------------

mkdir -p /var/lib/docker

cat <<EOF >> /etc/fstab
none /var/lib/docker tmpfs rw,relatime,size=10G 0 0
EOF

# Для поддержки запуска докера от пользователя
usermod -aG docker sandbox

# ---------------------------------------------------------------

cat <<'EOF' >> /usr/local/bin/trendocker-compose
#!/bin/bash
COMPOSE='docker-compose'

declare -A ENV_VARS
ENV_VARS=( \
  ["http_proxy"]="http://172.17.0.1:8888" \
  ["https_proxy"]="http://172.17.0.1:8888" \
  ["no_proxy"]="localhost,127.0.0.1" \
)

function construct_args {
  for k in "${!ENV_VARS[@]}"; do
    echo -n "$1 $k=${ENV_VARS[$k]} "
  done
}

CMD=$1
shift

if [ -z $CMD ]; then
  $COMPOSE
elif [ $CMD == 'run' ]; then
  $COMPOSE $CMD `construct_args "-e"` $@
elif [ $CMD == 'build' ]; then
  $COMPOSE $CMD `construct_args "--build-arg"` $@
else
  $COMPOSE $CMD $@
fi
EOF

chmod +x /usr/local/bin/trendocker-compose

# ---------------------------------------------------------------

cat <<'EOF' >> /usr/local/bin/trendocker
#!/bin/bash
DOCKER='docker'

CMD=$1
shift

if [ -z $CMD ]; then
  $DOCKER
elif [ $CMD == 'build' ]; then
  $DOCKER $CMD --network host $@
else
  $DOCKER $CMD $@
fi
EOF

chmod +x /usr/local/bin/trendocker

# ---------------------------------------------------------------

cat <<'EOF' >> /usr/local/bin/restore-docker-layers
#!/bin/bash

REMOTE_URL=$(git remote get-url --push origin)
DOCKER_CACHE_NAME=${1:-$REMOTE_URL}
DOCKER_CACHE_DEFAULT_BRANCH=${2:-master}
FILENAME="layers.lz"

if [ $DOCKER_CACHE_NAME ]; then
  echo "Docker cache warmup. Trying to fetch: $FILENAME for $DOCKER_CACKE_NAME"
  try_get()
  {
    echo "Getting docker layers for project $DOCKER_CACHE_NAME and branch: $1"
    curl -Gsf 'https://proxy.sandbox.yandex-team.ru/last/TRENDBOX_CI_RESOURCE_BETA' \
         --data-urlencode "attrs={\"type\": \"docker-cache\", \"project\": \"$DOCKER_CACHE_NAME\", \"branch\": \"$1\"}" \
         -o $FILENAME
  }
  try_get $TRENDBOX_BRANCH
  if [ ! -s $FILENAME -a -n $DOCKER_CACHE_DEFAULT_BRANCH ]; then
    try_get $DOCKER_CACHE_DEFAULT_BRANCH
  fi
  if [ -s $FILENAME ]; then
    plzip -t $FILENAME
    if [ $? -eq 0 ]; then
      echo "Archive OK"
      cat $FILENAME | plzip -d | docker load || true
    else
      echo "Archive NOT OK"
    fi
    rm -f $FILENAME
  fi
fi
EOF

chmod +x /usr/local/bin/restore-docker-layers


# ---------------------------------------------------------------

cat <<'EOF' >> /usr/local/bin/save-docker-layers
#!/bin/bash

REMOTE_URL=$(git remote get-url --push origin)
DOCKER_CACHE_NAME=${1:-$REMOTE_URL}
FILENAME="layers.lz"

if [ $DOCKER_CACHE_NAME ]; then
  docker save $(docker images -aq) | plzip -1 -f -o layers
  if [ -s $FILENAME ]; then
    trendbox publish-resource layers.lz --attr type=docker-cache \
                                        --attr project=$DOCKER_CACHE_NAME \
                                        --attr branch=$TRENDBOX_BRANCH
  fi
fi
EOF

chmod +x /usr/local/bin/save-docker-layers
