#!/bin/bash

set -eux
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)

get_bind_port () {
    # first argument is the config file path
    # second argument is a default port number if it is not found
    # in the config file
    bind_string=$(grep bind_port $1)
    if [ "$bind_string" != "" ]; then
        equals_index=$(expr index "$bind_string" "=")
        port_number=${bind_string:$equals_index}
        echo ${port_number/ /}
    else
        echo $2
    fi
}

OBJECT_PORT=$(get_bind_port /etc/swift/object-server.conf 6000)
CONTAINER_PORT=$(get_bind_port /etc/swift/container-server.conf 6001)
ACCOUNT_PORT=$(get_bind_port /etc/swift/account-server.conf 6002)

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\%/$OBJECT_PORT} 100
    swift-ring-builder /etc/swift/container.builder add ${DEVICE/\%PORT\%/$CONTAINER_PORT} 100
    swift-ring-builder /etc/swift/account.builder add ${DEVICE/\%PORT\%/$ACCOUNT_PORT} 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
