#!/bin/bash

## Should be executable N time in a row with same result.

. lib/common

set -e

named_uid=$(docker_get_uid "$SERVICE_NAME" "named")

LOGS=/var/log/bind
mkdir -p "$SERVICE_DATASTORE/$LOGS"
chown -R "$named_uid" "$SERVICE_DATASTORE/$LOGS"

rotated_count=$(relation-get rotated-count 2>/dev/null) || true
rotated_count=${rotated_count:-52}

## XXXvlab: a lot of this intelligence should be moved away into ``logrotate`` charm
DST="$CONFIGSTORE/$TARGET_SERVICE_NAME/etc/logrotate.d/$SERVICE_NAME"
file_put "$DST" <<EOF
/var/log/docker/$SERVICE_NAME/*.log
 {
    weekly
    missingok
    dateext
    dateyesterday
    dateformat _%Y-%m-%d
    extension .log
    rotate $rotated_count
    compress
    delaycompress
    notifempty
    create 640
    sharedscripts
    postrotate
        dc exec $SERVICE_NAME /usr/sbin/rndc reconfig > /dev/null 2>/dev/null || true
    endscript
}
EOF

config-add "\
services:
  $MASTER_TARGET_SERVICE_NAME:
    volumes:
      - $DST:/etc/logrotate.d/docker-${SERVICE_NAME}:ro
      - $SERVICE_DATASTORE$LOGS:/var/log/docker/$SERVICE_NAME:rw
  $MASTER_BASE_SERVICE_NAME:
    volumes:
      - $SERVICE_DATASTORE$LOGS:$LOGS:rw
"