#!/bin/sh -e

if [ "$AMI" = "yes" ]; then
    RAIDCNT=`grep xvdb /proc/mdstat | wc -l`
    RAIDDEV=`grep xvdb /proc/mdstat | awk '{print $1}'`

    if [ $RAIDCNT -ge 1 ]; then
        echo "RAID already constructed."
        if [ "`mount|grep /var/lib/scylla`" = "" ]; then
            mount -o noatime /dev/$RAIDDEV /var/lib/scylla
        fi
    else
        echo "RAID does not constructed, going to initialize..."

        if [ "$AMI_KEEP_VERSION" != "yes" ]; then
            yum update -y
        fi

        DISKS=""
        for i in /dev/xvd{b..z}; do
            if [ -b $i ];then
                echo "Found disk $i"
                if [ "$DISKS" = "" ]; then
                    DISKS=$i
                else
                    DISKS="$DISKS,$i"
                fi
            fi
        done

        if [ "$DISKS" != "" ]; then
            /usr/lib/scylla/scylla_raid_setup -d $DISKS
        fi

        /usr/lib/scylla/scylla-ami/ds2_configure.py
    fi
fi

if [ "$NETWORK_MODE" = "virtio" ]; then
    ip tuntap del mode tap dev $TAP
    ip tuntap add mode tap dev $TAP user $USER one_queue vnet_hdr
    ip link set dev $TAP up
    ip link set dev $TAP master $BRIDGE
    chown $USER.$GROUP /dev/vhost-net
elif [ "$NETWORK_MODE" = "dpdk" ]; then
    modprobe uio
    modprobe uio_pci_generic
    /usr/lib/scylla/dpdk_nic_bind.py --force --bind=uio_pci_generic $ETHPCIID
    for n in /sys/devices/system/node/node?; do
        echo $NR_HUGEPAGES > $n/hugepages/hugepages-2048kB/nr_hugepages
    done
else # NETWORK_MODE = posix
    if [ "$SET_NIC" = "yes" ]; then
        sudo sh /usr/lib/scylla/posix_net_conf.sh $IFNAME >/dev/null 2>&1 || true
    fi
fi
. /etc/os-release
if [ "$ID" = "ubuntu" ]; then
    hugeadm --create-mounts
fi
