#!/bin/bash

command=$1
shift

app_type=${app_type:-forms_int}
yenv_name=intranet
if [ "$app_type" == "forms_biz" ]; then
    yenv_name=other
fi
srcpath=$(realpath ${src:-src/})
testspath=$(realpath ${tests:-tests/})
arcadiapath=$HOME/arcadia

case $command in
    dev)
        command="service memcached start
                 && service redis-server start
                 && ln -fs /usr/share/zoneinfo/Europe/Moscow /etc/localtime"
        echo $command
        eval $command
        ;;
    server)
        command="app_type=$app_type
                 YENV_NAME=$yenv_name
                 YAUTH_USE_TVM2_FOR_BLACKBOX=1
                 PYTHONPATH=$srcpath
                 Y_PYTHON_SOURCE_ROOT=$arcadiapath
                 uwsgi/forms_uwsgi --ini=build/uwsgi-dev.ini"
        echo $command
        eval $command
        ;;
    celery)
        queue_name=${1:-integrations}
        shift
        command="app_type=$app_type
                 YENV_NAME=$yenv_name
                 PYTHONPATH=$srcpath
                 C_FORCE_ROOT=1
                 Y_PYTHON_SOURCE_ROOT=$arcadiapath
                 Y_PYTHON_ENTRY_POINT=events.manage:celery
                 uwsgi/forms_uwsgi worker -A events.celery_app -Q $queue_name -c 4 -l DEBUG $*"
        echo $command
        eval $command
        ;;
    beat)
        command="app_type=$app_type
                 YENV_NAME=$yenv_name
                 PYTHONPATH=$srcpath
                 C_FORCE_ROOT=1
                 Y_PYTHON_SOURCE_ROOT=$arcadiapath
                 Y_PYTHON_ENTRY_POINT=events.manage:celery
                 uwsgi/forms_uwsgi beat -A events.celery_app -l DEBUG -s /tmp/celery-beat-schedule --pidfile=/tmp/celery-beat.pid $*"
        echo $command
        eval $command
        ;;
    tests)
        command="ya make -A $(devtools/test_args.py $*)"
        echo $command
        eval $command
        ;;
    flush)
        command="echo 'flush_all' | nc localhost 11211"
        echo $command
        eval $command
        ;;
    *)
        command="app_type=$app_type
                 YENV_NAME=$yenv_name
                 PYTHONPATH=$srcpath
                 Y_PYTHON_SOURCE_ROOT=$arcadiapath
                 Y_PYTHON_ENTRY_POINT=events.manage:management
                 uwsgi/forms_uwsgi $command $*"
        echo $command
        eval $command
        ;;
esac
