#!/bin/bash
set -e

echo Starting rancher server
cd $(dirname $0)/..

CMD=bin/rancher
if [ ! -x $CMD ]; then
    ./scripts/build-server
fi

if [ ! -z $1 ] && ( [ $1 = "--trace" ] || [ $1 = "--info" ] || [ $1 = "--debug" ] ); then
  LOGFLAG=$1
fi

rm -rf build/testdata
mkdir -p build/testdata
cd build/testdata
export KUBECONFIG=
export CATTLE_DEV_MODE=yes
export CATTLE_SERVER_URL="https://$(ip route get 8.8.8.8 | awk '{print $7}'):8443"
export CATTLE_BOOTSTRAP_PASSWORD="admin"
export CATTLE_FEATURES="harvester=false"

#########################################################################################################################################
# DISCLAIMER                                                                                                                            #
# Copied from https://github.com/moby/moby/blob/ed89041433a031cafc0a0f19cfe573c31688d377/hack/dind#L28-L37                              #
# Permission granted by Akihiro Suda <akihiro.suda.cz@hco.ntt.co.jp> (https://github.com/rancher/k3d/issues/493#issuecomment-827405962) #
# Moby License Apache 2.0: https://github.com/moby/moby/blob/ed89041433a031cafc0a0f19cfe573c31688d377/LICENSE                           #
#########################################################################################################################################
# only run this if rancher is not running in kubernetes cluster and if the init cgroup does not already exist
if [ -f /sys/fs/cgroup/cgroup.controllers ] && [ ! -d /sys/fs/cgroup/init ]; then
  # move the processes from the root group to the /init group,
  # otherwise writing subtree_control fails with EBUSY.
  mkdir -p /sys/fs/cgroup/init
  xargs -rn1 < /sys/fs/cgroup/cgroup.procs > /sys/fs/cgroup/init/cgroup.procs || :
  # enable controllers
  sed -e 's/ / +/g' -e 's/^/+/' <"/sys/fs/cgroup/cgroup.controllers" >"/sys/fs/cgroup/cgroup.subtree_control"
fi

if [ $CI ]; then
  # DISCLAIMER
  # This code relies on the fact that our CI pipleine runs on one system at a time. Currently with drone this means that the setting `DRONE_AGENT_CONCURRENCY=1`

  # Attempt to find and stop any previous instances of dapper containers.
  # To combat the scenario where drone runners are reused and an instance of rancher is still running.
  echo "Checking for running containers from a previous build."

  # gets a list of all docker containers that were started in a CI build.
  dapper_containers=$(docker ps --format '{{.Names}}/{{.Label "DRONE_BUILD_NUMBER"}}' --filter 'label=CI=true')
  for container_info in $dapper_containers; do
    IFS='/' read -ra split_info <<<"$container_info"

    # remove containers that were not created in this build
    if [ "${split_info[1]}" != "${DRONE_BUILD_NUMBER}" ]; then
      echo "Removing old drone container ${split_info[0]}"
      docker stop ${split_info[0]}
      docker rm ${split_info[0]}
    fi
  done
fi

exec ../../$CMD $LOGFLAG