#!/bin/sh

is_ami() {
    if [ "`dmidecode --string system-version | grep \.amazon`" != "" ] && \
       [ "`curl http://169.254.169.254/latest/meta-data/ami-id | grep ami-`" != "" ]; then
         echo 1
    else
         echo 0
    fi
}

is_supported_instance_type() {
    TYPE=`curl http://169.254.169.254/latest/meta-data/instance-type|cut -d . -f 1`
    case $TYPE in
        "m3"|"c3"|"i2") echo 1;;
        *) echo 0;;
    esac
}

is_developer_mode() {
    echo $SCYLLA_ARGS|egrep -c "\-\-developer-mode(\s+|=)1"
}

if [ ! -f /etc/scylla/io_configured ] && [ `is_developer_mode` -eq 0 ]; then
    if [ `is_ami` -eq 1 ]; then
        SMP=`echo $SCYLLA_ARGS|sed -e "s/^.*smp\(\s\+\|=\)\([0-9]*\).*$/\2/"`
        CPUSET=`echo $SCYLLA_ARGS|sed -e "s/^.*\(--cpuset\(\s\+\|=\)[0-9\-]*\).*$/\1/"`
    fi
    if [ `is_ami` -eq 1 ] && [ `is_supported_instance_type` -eq 1 ]; then
        NR_CPU=`cat /proc/cpuinfo |grep processor|wc -l`
        NR_DISKS=`curl http://169.254.169.254/latest/meta-data/block-device-mapping/|grep ephemeral|wc -l`

        if [ "$SMP" != "" ]; then
            NR_CPU=$SMP
        fi
        NR_SHARDS=$NR_CPU
        if [ $NR_CPU -ge 8 ] && [ "$SET_NIC" = "no" ]; then
            NR_SHARDS=$((NR_CPU - 1))
        fi
        if [ $NR_DISKS -lt 2 ]; then NR_DISKS=2; fi

        NR_REQS=$((32 * $NR_DISKS / 2))

        NR_IO_QUEUES=$NR_SHARDS
        if [ $(($NR_REQS/$NR_IO_QUEUES)) -lt 4 ]; then
            NR_IO_QUEUES=$(($NR_REQS / 4))
        fi

        NR_REQS=$(($(($NR_REQS / $NR_IO_QUEUES)) * $NR_IO_QUEUES))

        echo "SCYLLA_IO=\"--num-io-queues $NR_IO_QUEUES --max-io-requests $NR_REQS\"" > /etc/scylla.d/io.conf
    else
        iotune --evaluation-directory /var/lib/scylla --format envfile --options-file /etc/scylla.d/io.conf $CPUSET
        if [ $? -ne 0 ]; then
            logger -p user.err "/var/lib/scylla did not pass validation tests, it may not be on XFS and/or has limited disk space."
            logger -p user.err "This is a non-supported setup, and performance is expected to be very bad."
            logger -p user.err "For better performance, placing your data on XFS-formatted directories is required."
            logger -p user.err " To override this error, see the developer_mode configuration option."
        fi
    fi
    touch /etc/scylla/io_configured
fi
