#!/bin/bash

set -e

DATASOURCES_FILE=/etc/yandex/tools-datasources/datasources.py

if [[ -z "$DEPLOY_STAGE_ID" ]]; then
  if [ "$YENV_TYPE" = 'development' ]; then
      mkdir -p /etc/yandex/tools-datasources/
      cp /intrasearch/settings/devds.py $DATASOURCES_FILE
      if [ -f '/intrasearch/.isearch' ]; then
          cat /intrasearch/.isearch >> $DATASOURCES_FILE
      fi
  fi
  chmod a+rx /etc/yandex /etc/yandex/tools-datasources/
  chmod a+r $DATASOURCES_FILE
else
  echo "Deploying in Y.Deploy"
fi


mkdir -p /ephemeral/redis/
chown redis:www-data /ephemeral/redis/

mkdir -p /var/run/log/isearch
chown www-data:www-data /var/run/log/isearch
mkdir -p /var/run/pid/isearch
chown www-data:www-data /var/run/pid/isearch

mkdir -p /var/run/yandex/intrasearch/redis
chown redis:www-data /var/run/yandex/intrasearch/redis
chown www-data /var/run/yandex/intrasearch/

touch /etc/authbind/byport/80
chown www-data:www-data /etc/authbind/byport/80
chmod 755 /etc/authbind/byport/80

if [ "$ISEARCH_COMPONENT" = 'celery' ]; then
    isearch celeryopts > /intrasearch/etc/supervisord/celery/celery.conf
    isearch celerybeatopts > /intrasearch/etc/supervisord/celery/celery-beat.conf
    mkdir -p /intrasearch/etc/saas && isearch saas_push_conf > /intrasearch/etc/saas/saas_push.conf
fi

if [ -f '/etc/yandex/intrasearch_robot' ]; then
    chown www-data:www-data /etc/yandex/intrasearch_robot
    mkdir -p /var/www/.ssh && chown www-data:www-data /var/www/.ssh
fi

# Если у скрипта есть аргументы, то он, скорее всего, запущен через docker run, и не нужно стартовать supervisord
if [ -z "$1" ]; then
    exec supervisord -c /intrasearch/etc/supervisord/supervisord.conf
else
    exec $@
fi
