#!/bin/sh

DEST="/etc/yandex/statbox-push-client/push-client.yaml"

if [ -e /etc/yandex/environment.type ]; then
    YANDEX_ENV=$(cat /etc/yandex/environment.type)
fi

if [ -e /etc/yandex/environment.direct_sandbox ]; then
    YANDEX_ENV="sandbox"
fi

if [ "$YANDEX_ENV" = "" ]; then
    YANDEX_ENV="development"
fi

case "$YANDEX_ENV" in
    production|prestable)
        SOURCE="/etc/yandex/statbox-push-client/push-client.production.yaml"
        ;;

    testing|development|devtest)
        SOURCE="/etc/yandex/statbox-push-client/push-client.testing.yaml"
        ;;

    sandbox)
        SOURCE="/etc/yandex/statbox-push-client/push-client.empty.yaml"
        ;;

    *)
        SOURCE="/etc/yandex/statbox-push-client/push-client.empty.yaml"
        ;;
esac

if [ -e $SOURCE ]; then
    ln -s -f -T $SOURCE $DEST || true
fi

ACCESS_LOGS_DIR=/var/log/ppc.yandex.ru

if [ ! -d $ACCESS_LOGS_DIR ]; then
    mkdir $ACCESS_LOGS_DIR && chown :adm $ACCESS_LOGS_DIR && chmod g+s $ACCESS_LOGS_DIR || true
fi

STATBOX_EXPORT_DIR=/opt/ppc-data/export/statbox
if [ ! -d $STATBOX_EXPORT_DIR ]; then
    mkdir -p $STATBOX_EXPORT_DIR || true
fi

#==Migration save position directory==

NEW_PWD="/local/cache/push-client"
OLD_PWD="/var/lib/push-client"
RESTART_CLIENT=0

/bin/mkdir -p $NEW_PWD ||:
/bin/mkdir -p $OLD_PWD ||:

NEW_COUNT=$( /bin/ls $NEW_PWD | grep -vE '*.init|*.service' |  /usr/bin/wc -l );
OLD_COUNT=$( /bin/ls $OLD_PWD | grep -vE '*.init|*.service' | /usr/bin/wc -l );

if [[ $OLD_COUNT != 0 && $NEW_COUNT != 0 ]]
then
   echo "Broken migration: not empty $OLD_PWD and $NEW_PWD" 
   exit 1
fi

if [[ $OLD_COUNT != 0 && $NEW_COUNT == 0 ]]
then
   echo "Start migration: move $OLD_PWD -> $NEW_PWD"
   /etc/init.d/statbox-push-client stop && sleep 2
   /usr/bin/pgrep -f 'yandex/statbox-push-client/push-client.yaml' && echo "Error migration: push-client dont stopped" && exit 2
   echo "Moving db $OLD_PWD -> $NEW_PWD"
   /bin/mv $OLD_PWD/* $NEW_PWD/ && RESTART_CLIENT=1;
else
   RESTART_CLIENT=1
   echo "state directory for push-client already $NEW_PWD";
fi

/bin/chown loadbase $NEW_PWD || true
/bin/chgrp statbox  $NEW_PWD || true
/bin/chown statbox:statbox -R $NEW_PWD/* || true
/usr/bin/find $NEW_PWD -type d -exec /bin/chmod 0775 -R {} \;
/usr/bin/find $NEW_PWD -type f -exec /bin/chmod 0664 -R {} \;

if [[ $RESTART_CLIENT == 1 ]]
then
   service statbox-push-client restart || true
fi
