#!/bin/bash

## Init is run on host
## For now it is run every time the script is launched, but
## it should be launched only once after build.

## Accessible variables are:
## - SERVICE_NAME        Name of current service
## - DOCKER_BASE_IMAGE   Base image from which this service might be built if any
## - SERVICE_DATASTORE           Location on host of the DATASTORE of this service
## - SERVICE_CONFIGSTORE         Location on host of the CONFIGSTORE of this service

set -e

uid=$(docker_get_uid "$SERVICE_NAME" "redis")

CONFIG=$SERVICE_CONFIGSTORE/etc/redis-local.conf

PASSWORD=$(options-get password 2>/dev/null) || {
    if [ -e "$CONFIG" ]; then
        PASSWORD=$(grep ^requirepass "$CONFIG" | sed -r 's/^requirepass\s+(.+)$/\1/g')
    fi
    if [ -z "$PASSWORD" ]; then
        info "Generating redis admin password"
        PASSWORD=$(gen_password 64)
    fi
}



mkdir -p "$(dirname "$CONFIG")"
cat <<EOF > "$CONFIG"
daemonize no
loglevel notice
logfile ""
bind 0.0.0.0
requirepass $PASSWORD

EOF
chown -v "$uid" "$CONFIG"


dirs=(/var/log/redis /var/lib/redis)
host_dirs=()
for dir in "${dirs[@]}"; do
    host_dirs+=("$SERVICE_DATASTORE$dir")
done

mkdir -p "${host_dirs[@]}"
find "${host_dirs[@]}" \! -user "$uid" -print0 | while read-0 f; do
    chown -v "$uid" "$f" || exit 1
done

config_hash=$(cat "$CONFIG" | md5_compat) || exit 1
init-config-add "
$MASTER_BASE_SERVICE_NAME:
  labels:
    - compose.config_hash=$config_hash
"