#!/bin/bash

######################################################################
#
#  Copyright (c) 2015 arakasi72 (https://github.com/arakasi72)
#
#  --> Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php
#
######################################################################

PATH=/usr/local/bin:/usr/bin:/usr/local/sbin:/usr/sbin:/bin:/sbin

rundir=$(dirname $(readlink -f $0))
branch=$1

if [ "$(id -u)" != "0" ]; then
  echo "Must be run as root, directly or with sudo"
  exit 1
fi

if [ $(dpkg-query -W -f='${Status}' git 2>/dev/null | grep -c "ok installed") -eq 0 ]; then
echo "Installing git"
apt-get -yqq install git 2>&1 >> /dev/null
fi

if [ $(dpkg-query -W -f='${Status}' ca-certificates 2>/dev/null | grep -c "ok installed") -eq 0 ]; then
echo "Installing ca-certificates"
apt-get -yqq install ca-certificates 2>&1 >> /dev/null
fi


if [ -d /etc/rtinst ] && [ -z $branch ]; then
  cd /etc/rtinst
  branch=$(basename "$(git symbolic-ref -q HEAD)")
  if [ -z $branch ]; then
    branch=$(git describe --tags --exact-match)
  fi
  if [ $(git ls-remote --tags --heads https://github.com/arakasi72/rtinst.git $branch | wc -l) -eq 0 ]; then
    echo "$branch has been deleted, using latest numbered release instead"
    branch=release
  fi
fi

if [ -z $branch ] || [ $branch = release ]; then
  branch=$(basename "$(git ls-remote --tags https://github.com/arakasi72/rtinst.git | grep -o 'refs/tags/v.*' | sort -V | tail -1)")
  if [ -z $branch ]; then
    echo "Could not find a numbered release, using master instead"
    branch=master
  fi
fi

if [ $(git ls-remote --tags --heads https://github.com/arakasi72/rtinst.git $branch | wc -l) -eq 0 ]; then
  echo "Could not find $branch, please try again"
  exit
fi

cd
rm -fr /etc/rtinst
git clone -q https://github.com/arakasi72/rtinst.git /etc/rtinst
cd /etc/rtinst
git checkout $branch
cd
ln -sf /etc/rtinst/scripts/* /usr/local/bin
ln -sf /etc/rtinst/rtsetup /usr/local/bin

if [ "$rundir" != "/etc/rtinst" ]; then
    rm -f $rundir/rtsetup
fi
