#!/bin/sh

CONFIG="/etc/yandex/statbox-push-client/push-client.yaml"
CONFIG_OLD="/etc/yandex/statbox-push-client/push-client.yaml.old"

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 | /bin/grep -vE 'push-client.init|push-client.service' | /usr/bin/wc -l );
OLD_COUNT=$( /bin/ls $OLD_PWD | /bin/grep -vE 'push-client.init|push-client.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/chgrp statbox /var/log/mysql.*/ptkill-query.log{,.*} || true
/bin/chgrp statbox /opt/mysql.*/data/audit.log{,.*} || 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 {} \;
#===

/usr/sbin/generate-mysql-push-client-config ||:

DIFF=$(/usr/bin/diff $CONFIG $CONFIG_OLD);
if [[ -n $DIFF ]]
then
   RESTART_CLIENT=1
fi

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