#!/usr/bin/env sh
PATH=/opt/remi/php56/root/usr/bin/:$PATH

if [ -x /usr/local/bin/drush ] && [ -f /var/www/corpusdelaparole/drupal/sites/default/settings.php ]; then
    echo "Apply database update"
    /usr/local/bin/drush -r /var/www/corpusdelaparole/drupal updb -y
    echo "Reactivate corpus module"
    /usr/local/bin/drush -r /var/www/corpusdelaparole/drupal pm-enable -y corpus

    echo "Emptying accesslog,search_dataset,search_index,search_total,sessions,watchdog tables"
    /usr/local/bin/drush -r /var/www/corpusdelaparole/drupal sql-query "TRUNCATE TABLE accesslog"
    /usr/local/bin/drush -r /var/www/corpusdelaparole/drupal sql-query "TRUNCATE TABLE search_dataset"
    /usr/local/bin/drush -r /var/www/corpusdelaparole/drupal sql-query "TRUNCATE TABLE search_index"
    /usr/local/bin/drush -r /var/www/corpusdelaparole/drupal sql-query "TRUNCATE TABLE search_total"
    /usr/local/bin/drush -r /var/www/corpusdelaparole/drupal sql-query "TRUNCATE TABLE sessions"
    /usr/local/bin/drush -r /var/www/corpusdelaparole/drupal sql-query "TRUNCATE TABLE watchdog"

    echo "Clear drupal cache"
    /usr/local/bin/drush -r /var/www/corpusdelaparole/drupal cc all

fi

if [ -d /var/www/corpusdelaparole/corpus-back/ ]; then
    pushd /var/www/corpusdelaparole/corpus-back/ > /dev/null

    echo "Migrating back office database"
    php artisan migrate -n --force

    echo "Optimizing framework"
    php artisan optimize
    php artisan config:cache
    php artisan route:cache

    echo "Correcting file permissions for back office"
    chgrp -R apache storage bootstrap/cache
    chmod -R ug+rwx storage bootstrap/cache

    echo "Put back application in production"
    php artisan up

    popd > /dev/null
fi

echo "Restart httpd"
/usr/bin/systemctl restart httpd
