#!/bin/bash
# Copyright (C) The Arvados Authors. All rights reserved.
#
# SPDX-License-Identifier: AGPL-3.0

. /usr/local/lib/arvbox/common.sh

set -eu -o pipefail

if ! [[ -d /tmp/arvbox-ready ]] ; then
   echo "Note: if this is a fresh arvbox installation, it may take 10-15 minutes (or longer) to download and"
   echo "install dependencies.  Use \"arvbox log\" to monitor the progress of specific services."
   echo
   mkdir -p /tmp/arvbox-ready
fi

sleep 3

waiting=""

for s in "${!services[@]}"
do
  if ! [[ -f /tmp/arvbox-ready/$s ]] ; then
    if nc -z localhost ${services[$s]} ; then
      echo "$s is ready at $localip:${services[$s]}"
      touch /tmp/arvbox-ready/$s
    else
      waiting="$waiting $s"
    fi
  fi
done

if ! docker version >/dev/null 2>/dev/null ; then
  waiting="$waiting docker"
fi

for sdk_app in arv arv-get cwl-runner arv-mount ; do
    if ! which $sdk_app >/dev/null ; then
        waiting="$waiting sdk"
        break
    fi
done

if ! (ps ax | grep -v grep | grep "crunch-dispatch") > /dev/null ; then
    waiting="$waiting crunch-dispatch"
fi

export ARVADOS_API_HOST=$localip:${services[controller-ssl]}
export ARVADOS_API_HOST_INSECURE=1

vm_ok=0
if test -s $ARVADOS_CONTAINER_PATH/vm-uuid -a -s $ARVADOS_CONTAINER_PATH/superuser_token; then
    vm_uuid=$(cat $ARVADOS_CONTAINER_PATH/vm-uuid)
    export ARVADOS_API_TOKEN=$(cat $ARVADOS_CONTAINER_PATH/superuser_token)
    if (which arv && arv virtual_machine get --uuid $vm_uuid) >/dev/null 2>/dev/null ; then
        vm_ok=1
    fi
fi

if test $vm_ok = 0 ; then
    waiting="$waiting vm"
fi

if ! [[ -f /tmp/banner-ready ]] ; then
    waiting="$waiting banner"
fi

if ! [[ -z "$waiting" ]] ; then
    if ps x | grep -v grep | grep "bundle install" > /dev/null; then
        gemcount=$(ls /var/lib/arvados/lib/ruby/gems/*/gems /var/lib/arvados-arvbox/.gem/ruby/*/gems 2>/dev/null | wc -l)
        lockfile=/usr/src/arvados/services/api/Gemfile.lock
        gemlockcount=$(cat $lockfile \
                           | grep -vE "(GEM|PLATFORMS|DEPENDENCIES|BUNDLED|GIT|$^|remote:|specs:|revision:)" \
                           | sed 's/^ *//' | sed 's/(.*)//' | sed 's/ *$//' | sort | uniq | wc -l)
        waiting="$waiting (installing ruby gems $gemcount of about $gemlockcount)"
    fi

    if ps x | grep -v grep | grep "c++.*/var/lib/passenger" > /dev/null ; then
        waiting="$waiting (compiling passenger)"
    fi

    if ps x | grep -v grep | grep "pip install" > /dev/null; then
        waiting="$waiting (installing python packages)"
    fi
    echo "    Waiting for$waiting ..."
    exit 1
fi

echo
echo "Your Arvados-in-a-box is ready!"
echo "Workbench2 is hosted at https://$localip:${services[workbench2-ssl]}"
echo "Documentation is hosted at http://$localip:${services[doc]}"

rm -r /tmp/arvbox-ready
