#!/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
}

backup_database() {
  year_month=$(date +%Y%m)
  backup_date=$(date +%Y%m%d_%H%M)
  mkdir -p foo "/root/medicine-backups/${year_month}"
  docker exec -i medicine-stack-postgres \
    pg_dump --no-owner -U postgres -F c \
    medicine > "/root/medicine-backups/${year_month}/${backup_date}_database.tar.gz" \
    --exclude-table-data=riisz_logging --exclude-table-data=reversion_*
}

post_update() {
  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
  backup_database

  docker-compose stop
  docker-compose up -d

  post_update

  docker_cleanup
}

fast_update() {
  pull_images
  docker-compose run --rm app python manage.py migrate --noinput
  docker-compose stop
  docker-compose up -d

  docker_cleanup
}

${COMMAND}