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

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

print_usage() {
    echo "scylla_install_pkg --local-pkg /home/scylla/rpms --unstable"
    echo "  --local-pkg	install locally built .rpm/.deb on specified directory"
    echo "  --unstable  use unstable repository"
    exit 1
}

LOCAL_PKG=
UNSTABLE=0
while [ $# -gt 0 ]; do
    case "$1" in
        "--local-pkg")
            LOCAL_PKG=$2
            shift 2
            ;;
        "--unstable")
            UNSTABLE=1
            shift 1
            ;;
        *)
            print_usage
            shift 1
            ;;
    esac
done

. /etc/os-release

if [ "$ID" = "ubuntu" ]; then
    if [ "$LOCAL_PKG" = "" ]; then
        echo "deb http://s3.amazonaws.com/downloads.scylladb.com/deb/ubuntu trusty/scylladb multiverse" > /etc/apt/sources.list.d/scylla.list
        apt-get update
        apt-get install -y --force-yes scylla-server scylla-jmx scylla-tools
    else
        apt-get install -y --force-yes gdebi-core
        gdebi $LOCAL_PKG/scylla-server*.deb $LOCAL_PKG/scylla-jmx*.deb $LOCAL_PKG/scylla-tools*.deb
    fi
else
    if [ "$ID" = "fedora" ]; then
        if [ $UNSTABLE -eq 0 ]; then
            curl http://downloads.scylladb.com/rpm/fedora/scylla.repo > /etc/yum.repos.d/scylla.repo
        else
            curl http://downloads.scylladb.com.s3.amazonaws.com/rpm/unstable/fedora/master/latest/scylla.repo > /etc/yum.repos.d/scylla.repo
        fi
    elif [ "$ID" = "centos" ] || [ "$ID" = "rhel" ]; then
        if [ $UNSTABLE -eq 0 ]; then
            curl http://downloads.scylladb.com/rpm/centos/scylla.repo > /etc/yum.repos.d/scylla.repo
        else
            curl http://downloads.scylladb.com.s3.amazonaws.com/rpm/unstable/centos/master/latest/scylla.repo > /etc/yum.repos.d/scylla.repo
        fi
        yum install -y epel-release
    else
        echo "Unsupported distribution"
        exit 1
    fi

    if [ "$LOCAL_PKG" = "" ]; then
        yum install -y scylla-server scylla-server-debuginfo scylla-jmx scylla-tools
    else
        yum install -y $LOCAL_PKG/scylla-server*.x86_64.rpm $LOCAL_PKG/scylla-jmx*.noarch.rpm $LOCAL_PKG/scylla-tools*.noarch.rpm
    fi
fi
