#!/bin/bash

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

## if I'm linked to a schedule-command, then add the scheduler dependency to source service
if read-0 ts _ _ < <(get_service_relation "$SERVICE_NAME" "schedule-command"); then
    if [ "$ts" != "$MASTER_BASE_SERVICE_NAME" ]; then
        config-add "\
services:
  $MASTER_BASE_SERVICE_NAME:
    depends_on:
      - \"$ts\"
"
    fi
fi

exit 0

. lib/common

set -e

LOGS=/var/log/apache2



## XXXvlab: hum it seems apache logging is run as root, so well...
# logs_creds=$(cached_cmd_on_base_image apache "stat -c '%u %g' '$LOGS'") || {
#     debug "Failed to query for www-data gid in ${DARKYELLOW}apache${NORMAL} base image."
#     return 1
# }

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
##
##  Issues:
##  - relation-joined will execute first log-rotate charm part of the
##    relation, which is not what we want here, as we need to send
##    default value for the creation of the config file on the server
##    part.
##  - we need to send the directory it seems, otherwise, docker will
##    create directory when the log file is missing, and I'm not sure
##    how processes will react when their file is moved out of their
##    file-system scope when rotated (but I think there will be no
##    issue here).
##    The problem here is that we can't cleanly put all file in the
##    same directory (and there are collision possible anyway).
##    This means that if we want more than one target, we need
##    sub-directories.
##    - For this issue, we only fear the 'docker' run and mounting
##      moment, and we are sure to run before, so we can make sure to
##      ``touch`` the files.
##    - can we move file that was been bound in a docker ? Well yes,
##      but it won't change place in the docker:( ... I guess you need
##      to reload the docker and the binding to work.
##

DST="$CONFIGSTORE/$TARGET_SERVICE_NAME/etc/logrotate.d/$SERVICE_NAME"
file_put "$DST" <<EOF
/var/log/docker/$SERVICE_NAME/*error.log
/var/log/docker/$SERVICE_NAME/*access.log
 {
    weekly
    missingok
    dateext
    dateyesterday
    dateformat _%Y-%m-%d
    extension .log
    rotate $rotated_count
    compress
    delaycompress
    notifempty
    create 640 root root
    sharedscripts
    postrotate
        docker-send-signal \$${MASTER_BASE_CHARM_NAME^^}_NAME SIGUSR1;
    endscript
}
EOF

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