#!/bin/sh

set -e

COMMAND="$1"
ARGUMENT="$2"

pull_images() {
  echo "readonly" | docker login docker.med-logic.ru --username readonly --password-stdin
  docker pull docker.med-logic.ru/medicine-app:latest
  docker pull docker.med-logic.ru/medicine-nginx:latest
}

post_update() {
  docker-compose run --rm app python manage.py migrate directory --noinput
  docker-compose run --rm app python manage.py directory_importdata all
  docker-compose run --rm app python manage.py migrate --noinput
  docker-compose run --rm app python manage.py collectstatic --noinput
  docker-compose run --rm app python manage.py post_update
}

docker_cleanup() {
  docker rmi $(docker images -f "dangling=true" -q)
}

update() {
  pull_images

  docker-compose stop
  docker-compose up -d

  post_update

  docker_cleanup
}

${COMMAND}