#!/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
    echo "#!/bin/sh" >> /usr/sbin/policy-rc.d
    echo "exit 101" >> /usr/sbin/policy-rc.d
    chmod +x /usr/sbin/policy-rc.d
    cp /etc/hosts /etc/hosts.orig
    echo 127.0.0.1 `hostname` >> /etc/hosts
    if [ $UNSTABLE -eq 0 ]; then
        echo "deb http://s3.amazonaws.com/downloads.scylladb.com/deb/ubuntu trusty/scylladb multiverse" > /etc/apt/sources.list.d/scylla.list
    else
        echo "deb https://s3.amazonaws.com/downloads.scylladb.com/deb/unstable/ubuntu/master/latest trusty/scylladb multiverse" > /etc/apt/sources.list.d/scylla.list
    fi
    apt-get update
    if [ "$LOCAL_PKG" = "" ]; then
        apt-get install -y --force-yes scylla-server scylla-jmx scylla-tools
    else
        if [ ! -f /usr/bin/gdebi ]; then
            apt-get install -y --force-yes gdebi-core
        fi
        echo Y | gdebi $LOCAL_PKG/scylla-server*.deb
        echo Y | gdebi $LOCAL_PKG/scylla-jmx*.deb
        echo Y | gdebi $LOCAL_PKG/scylla-tools*.deb
    fi
    mv /etc/hosts.orig /etc/hosts
    rm /usr/sbin/policy-rc.d
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
