#!/bin/bash

# Install and prepare infocalypse on your system.

default="$HOME/.local/hgext"
defaulthost="http://127.0.0.1:8888"

echo -n "Where do you store your Mercurial plugins? [$default]: "
read hgext
if [ "$hgext" == "" ]; then
    hgext="$default"
fi

echo -n "On which host and port does your node run? [$defaulthost]: "
read host
if [ "$host" == "" ]; then
    urlhost="$defaulthost"
fi

# get the bare host part for infocalypse --fcphost
arr=(${urlhost//:\/\// })
var=${arr[1]}
arr=(${var//:/ })
host=${arr[0]}

# enter hgext. Create it if necessary and requested
cd $hgext
if [ "$?" != "0" ]; then
    echo -n "Folder \"$hgext\" does not exist. Create it? [Y/n] "
    read create
    if [ "$create" != "n" ]; then 
        if [ "$hgext" == "$default" ]; then
            mkdir $HOME/.local/
        fi
        mkdir $hgext
    fi
fi
if [ "$?" != "0" ]; then
    echo "Could not create folder $hgext. Please do it by hand."
    exit
fi
cd $hgext

# Get the dependencies from the distro, where possible
distro () {
    if which apt-get >&/dev/null; then
        dist="debian"
    fi
    if which emerge >&/dev/null; then
        dist="gentoo"
    fi
    if which zypper >&/dev/null; then
        dist="opensuse"
    fi
    echo $dist
}

dist=$(distro)

get_dependencies_distro () {
    if [ "$1" == "gentoo" ]; then
        echo sudo emerge mercurial dulwich
        sudo emerge mercurial dulwich
    fi
    if [ "$1" == "debian" ]; then
        echo sudo apt-get install mercurial python-dulwich
        sudo apt-get install mercurial python-dulwich
    fi
    if [ "$1" == "opensuse" ]; then
        echo sudo zypper install mercurial python-dulwich
        sudo zypper install mercurial python-dulwich
    fi
}

get_dependencies_distro $dist

echo "Getting the needed hg repos."
hg clone http://bitbucket.org/durin42/hg-git
hg init infocalypse
cd infocalypse
wget ${urlhost}/USK@CiKlAk~D2IZ3cJye0R5VPp0nRRUB-zKd6L5hy9qvlkE,qaG86acZQy0I5stLe5wOCt61-GQDT~h-NQ~7C2nl-lc,AQACAAE/infocalypse-for-code-sharing/3/infocalypse.bundle
hg pull infocalypse.bundle
hg update

echo "Enabling the hggit and infocalypse extensions"
echo "
[extensions]
infocalypse = $(pwd)/infocalypse
hggit = $hgext/hg-git/hggit
" >> ~/.hgrc

echo "Running the infocalypse setup"
hg fn-setup
echo "Updating infocalypse from the official repo of djk"
hg fn-pull --fcphost $host --aggressive --uri USK@kRM~jJVREwnN2qnA8R0Vt8HmpfRzBZ0j4rHC2cQ-0hw,2xcoQVdQLyqfTpF2DpkdUIbHFCeL4W~2X1phUYymnhM,AQACAAE/wiki_hacking.R1/24
echo "Getting further updates from the repo of ArneBab"
hg fn-pull --fcphost $host --aggressive --uri USK@j2Mfv0b81MNSslh3Qg9gs1vgQj36whsuosP8ydZq158,Xb~vh8XEXmdwGFca4HAx-ILOZD6AWPVuRzIuLerl4PU,AQACAAE/infocalypse-repo.R1/1

echo "Setup finished. Enjoy using Infocalypse."