set -e

cd "$(dirname "$0")"

echo "=== Building L1 ==="
docker build --build-arg CACHEBUST=$(date +%s) -f l1/Dockerfile -t registry.rose-ash.com:5000/celery-l1-server:latest .

echo "=== Building L2 ==="
docker build --build-arg CACHEBUST=$(date +%s) -f l2/Dockerfile -t registry.rose-ash.com:5000/l2-server:latest .

echo "=== Removing stacks ==="
docker stack rm celery
docker stack rm activitypub

sleep 30

echo "=== Removing volumes ==="
docker volume rm activitypub_l2_data
docker volume rm activitypub_postgres_data
docker volume rm activitypub_ipfs_data
docker volume rm celery_l1_cache
docker volume rm celery_redis_data
docker volume rm celery_ipfs_data
docker volume rm celery_postgres_data

echo "=== Redeploying celery stack ==="
cd l1 && source .env && docker stack deploy -c docker-compose.yml celery && cd ..

echo "=== Redeploying activitypub stack ==="
cd l2 && source .env && docker stack deploy -c docker-compose.yml activitypub && cd ..

sleep 30

docker service update --force celery_l1-worker
docker service update --force celery_l1-server
docker service update --force celery_flower
docker stack services celery

docker service update --force activitypub_l2-server
docker stack services activitypub

echo "=== Restarting proxy nginx ==="
docker service update --force proxy_nginx
