#!/bin/bash

# check root
if [ "$EUID" -ne 0 ]
  then echo "Please run as root"
  exit 1
fi

# ubuntu only
if grep -qi ubuntu /etc/issue; then
    add-apt-repository universe
fi

# install required tools
apt-get update
apt-get install -y git make

# target selection
choices="1:2:3"
while [[ ":${choices}:" != *:${choice}:* ]]; do
    echo -e "What are you deploying?"
    echo -e "\\t1. MediaServer (default)"
    echo -e "\\t2. MediaWorker"
    echo -e "\\t3. MediaVault"
    read -r -p "Choice: [1] " choice
    [ -z "$choice" ] && choice=1
done

[ $choice = 1 ] && target=mediaserver
[ $choice = 2 ] && target=mediaworker
[ $choice = 3 ] && target=mediavault

# configure proxy
read -r -p "HTTP proxy (e.g. proxy.example.net:3128, enter to skip):" proxy
if [ "$proxy" ]; then
    git config --global http.sslVerify false
    git config --global http.proxy "$proxy"
    echo "HTTP_PROXY=\"http://$proxy\"" >> /etc/environment
    echo "HTTPS_PROXY=\"http://$proxy\"" >> /etc/environment
fi

# clone envsetup
git clone https://mirismanager.ubicast.eu/git/mediaserver/envsetup.git -b stable
cd /root/envsetup || exit

# activation key
read -r -p "Activation key (e.g. XXX-XXX-XXX-XXX): " key
if [ "$key" ]; then
    cp -u /root/envsetup/inventories/local-${target}/host_vars/localhost.{dist.yml,yml}
    # temp fix while waiting for envsetup3 to be merged into stable
    test -f site.yml || git checkout master
    sed -i "s/skyreach_activation_key:.*/skyreach_activation_key: ${key}/g" /root/envsetup/inventories/local-${target}/host_vars/localhost.yml
fi

# deploy target
make install
make deploy i=inventories/local-${target}
