#!/bin/bash

set -eu
set -o pipefail

PARTPOWER=$(os-apply-config --key swift.part-power --key-default 10)
REPLICAS=$(os-apply-config --key swift.replicas --key-default 1)
DEVICES=$(os-apply-config --key swift.devices --key-default "" --type raw)
ZONES=$(os-apply-config --key swift.zones --key-default 1)

if [ -z "$DEVICES" ] ; then
    echo "No swift devices to configure"
    exit 1
fi

swift-ring-builder /etc/swift/object.builder create $PARTPOWER $REPLICAS 1
swift-ring-builder /etc/swift/container.builder create $PARTPOWER $REPLICAS 1
swift-ring-builder /etc/swift/account.builder create $PARTPOWER $REPLICAS 1

# Function to place server in its zone.  Zone is calculated by
# server number in heat template modulo the number of zones + 1.
function place_in_zone () {
    local zone=$(echo $1 | sed -r 's/.*(z%[A-Za-z]+)([0-9]+)(%).*/\2/')
    local new_addr=$(echo "$1 $zone" | awk -v zones=$ZONES '
      {gsub(/z%[A-Za-z]+([0-9]+)%/,"z"($2%zones + 1), $1); print $1}')
    echo "$new_addr"
}

for DEVICE in ${DEVICES//,/ } ; do
    DEVICE=$(place_in_zone $DEVICE)
    swift-ring-builder /etc/swift/object.builder add ${DEVICE/\%PORT\%/6000} 100
    swift-ring-builder /etc/swift/container.builder add ${DEVICE/\%PORT\%/6001} 100
    swift-ring-builder /etc/swift/account.builder add ${DEVICE/\%PORT\%/6002} 100
done

swift-ring-builder /etc/swift/object.builder rebalance 999
swift-ring-builder /etc/swift/container.builder rebalance 999
swift-ring-builder /etc/swift/account.builder rebalance 999

chown root:swift /etc/swift/*.ring.gz
chmod g+r /etc/swift/*.ring.gz
