#!/bin/bash

SERVER_ADDRESS=37.205.11.28
PROJECT_NAME=portalsekask

echo "SPUSTA SA NPM"
sh npm.sh run prod

echo "CISTI SA CACHE PROJEKTU..."
php artisan cache:clear --no-interaction
php artisan view:clear --no-interaction

echo ""
echo "VYTVARA SA ARCHIV PROJEKTU PRE PRENOS NA CIELOVY SERVER..."
tar \
--exclude='./storage/logs/*' \
--exclude='./storage/framework/views/*.php' \
--exclude='./storage/framework/cache/data/*.*' \
--exclude='./storage/framework/sessions/*.*' \
--exclude='./storage/framework/testing' \
--exclude='./storage/app/public/files/shares/*.*' \
--exclude='./storage/app/public/photos/shares/*.*' \
-cvf ./docker/phpfpm/prod/project.tar ./app ./artisan ./bootstrap ./composer.json ./core ./config \
	./database/factories ./database/migrations ./database/seeds/*.php ./public ./resources/lang \
	./resources/views ./routes ./storage ./server.php

echo ""
echo "ZACINA KOPIROVANIE SUBOROV PROJEKTU NA CIELOVY SERVER..."
scp -rC ./docker admin@$SERVER_ADDRESS:/var/www/$PROJECT_NAME

echo ""
echo "ZACINA SA VYTVORENIE A SPUSTENIE PROJEKTU NA CIELOVOM SERVERE..."
ssh admin@$SERVER_ADDRESS "cd /var/www/$PROJECT_NAME/docker \
&& set COMPOSE_HTTP_TIMEOUT=5000 \
&& docker-compose -f docker-compose_prod.yml -p $PROJECT_NAME build --no-cache phpfpm \
&& docker-compose -f docker-compose_prod.yml -p $PROJECT_NAME stop phpfpm \
&& docker-compose -f docker-compose_prod.yml -p $PROJECT_NAME rm -f phpfpm \
&& docker-compose -f docker-compose_prod.yml -p $PROJECT_NAME up -d --build \
&& docker rmi $(docker images --filter "dangling=true" -q) \
&& docker rmi $(docker images | grep "none" | awk '/ / { print $3 }') \
&& docker rm $(docker ps -qa --no-trunc --filter "status=exited") \
&& exit"

rm -rf ./docker/phpfpm/prod/project.tar
