#!/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)
MIN_PART_HOURS=$(os-apply-config --key swift.min-part-hours --key-default 1)
BUILD_RINGS=$(os-apply-config --key swift.ring-build --key-default "True" | tr '[:upper:]' '[:lower:]')

if [ "$BUILD_RINGS" == "false" ] || [ "$BUILD_RINGS" == "f" ]; then
    echo "Won't build rings"
    exit 0
fi

get_bind_port () {
    # first argument is the config file path
    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 ""
    fi
}

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

if [ -z "$OBJECT_PORT" -o -z "$CONTAINER_PORT" -o -z "$ACCOUNT_PORT" ] ; then
    echo "Not all swift bind_ports are specified:"
    echo "/etc/swift/object-server.conf ($OBJECT_PORT)"
    echo "/etc/swift/container-server.conf ($CONTAINER_PORT)"
    echo "/etc/swift/account-server.conf ($ACCOUNT_PORT)"
    exit 1
fi

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

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

# 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
