#!/bin/sh -e
#
#  Copyright (C) 2015 ScyllaDB

if [ "`id -u`" -ne 0 ]; then
    echo "Requires root permission."
    exit 1
fi

print_usage() {
    echo "scylla_setup -d /dev/hda,/dev/hdb... -n eth0 -a"
    echo "  -d  specify disks for RAID"
    echo "  -n  specify NIC"
    echo "  -a  setup AMI instance"
    exit 1
}

NIC=eth0
RAID=/dev/md0
AMI=0
while getopts d:n:al:h OPT; do
    case "$OPT" in
        "n")
            NIC=$OPTARG
            ;;
        "d")
            DISKS=$OPTARG
            ;;
        "a")
            AMI=1
            ;;
        "h")
            print_usage
            ;;
    esac
done

SYSCONFIG_SETUP_ARGS="-n $NIC"
. /etc/os-release

if [ "$ID" != "ubuntu" ]; then
    if [ "`sestatus | awk '{print $3}'`" != "disabled" ]; then
        setenforce 0
        sed -e "s/enforcing/disabled/" /etc/sysconfig/selinux > /tmp/selinux
        mv /tmp/selinux /etc/sysconfig/
    fi
    if [ $AMI -eq 1 ]; then
        SYSCONFIG_SETUP_ARGS="$SYSCONFIG_SETUP_ARGS -N -a"
        if [ "$LOCAL_PKG" = "" ]; then
            yum update -y
        else
            SYSCONFIG_SETUP_ARGS="$SYSCONFIG_SETUP_ARGS -k"
        fi
        grep -v ' - mounts' /etc/cloud/cloud.cfg > /tmp/cloud.cfg
        mv /tmp/cloud.cfg /etc/cloud/cloud.cfg
        mv /home/centos/scylla-ami /usr/lib/scylla/scylla-ami
        chmod a+rx /usr/lib/scylla/scylla-ami/ds2_configure.py
    fi
    systemctl enable scylla-server.service
    systemctl enable scylla-jmx.service
fi
if [ $AMI -eq 0 ]; then
    /usr/lib/scylla/scylla_ntp_setup
    /usr/lib/scylla/scylla_bootparam_setup
    if [ $DISKS != "" ]; then
        /usr/lib/scylla/scylla_raid_setup -d $DISKS -u
        /usr/lib/scylla/scylla_coredump_setup -s
    else
        /usr/lib/scylla/scylla_coredump_setup
    fi
else
    /usr/lib/scylla/scylla_coredump_setup -s
    /usr/lib/scylla/scylla_ntp_setup -a
    /usr/lib/scylla/scylla_bootparam_setup -a
fi
/usr/lib/scylla/scylla_sysconfig_setup $SYSCONFIG_SETUP_ARGS
