#!/bin/bash
set -eux

function python-install() {
  local name=$1
  local svc_root=$2

  pushd /opt/stack/venvs
  SITE_PCKGS="--no-site-packages"
  # Nova depends on python-libvirt which can't be installed via pip
  if [ $name == "nova" ]; then
    SITE_PCKGS="--system-site-packages"
  fi
  virtualenv $SITE_PCKGS $name
  popd

  set +u
  source /opt/stack/venvs/$name/bin/activate
  set -u

  if [ -e $svc_root/requirements.txt ]; then
    reqs=$svc_root/requirements.txt
  elif [ -e $svc_root/tools/pip-requires ]; then
    reqs=$svc_root/tools/pip-requires
  else
    reqs=""
  fi

  # bug #1201253 : virtualenv-1.10.1 embeds setuptools-0.9.8, which
  # doesn't manage correctly HTTPS sockets when downloading pbr from
  # https://pypi.python.org/simple/ if using http_proxy and
  # https_proxy envvars
  pip install -U 'setuptools>=1.0'

  if [ -n "$reqs" ] ; then
       pip install -r $reqs
       # FIXME: pip requires doesn't include MySQL-python
       pip install MySQL-python
  fi

  pip install $svc_root

  set +u
  deactivate
  set -u
}


function install-os-service() {
  local user=$1
  local repo=$(echo $2 | sed 's/github.com/review.openstack.org/')
  local branch=$3

  id $user || useradd $user --system -d /var/run/$user -s /bin/false

  install -d -m 0750 -o $user -g $user /etc/$user

  local svc_root=/opt/stack/$user
  local git_dir="--git-dir $svc_root/.git"

  # if the repository is an absolute local path then
  # we assume its present, on the correct branch and use it
  # this would be the case when the source was retrieved by
  # the source-repositories element
  if [ "${repo:0:1}" = "/" ] ; then
    python-install $user $repo
  elif [ ! -e $svc_root ]; then
    git clone --depth=1 -b $branch $repo $svc_root
    python-install $user $svc_root
  else
    if ! git $git_dir remote -v | grep $repo; then
      echo "ERROR: $svc_root exists and did not come from $repo"
      exit 1
    fi
    actual_rev=$(git $git_dir show | head -1 | awk '{print $2}')
    git $git_dir checkout $branch
    expected_rev=$(git $git_dir show | head -1 | awk '{print $2}')
    if [ "$expected_rev" != "$actual_rev" ]; then
      echo "ERROR: $repo exists and is not on rev $branch"
      exit 1
    fi
  fi
}


function usage() {
  echo "options:"
  echo "  -h   show usage and exit"
  echo "  -r   service's git repo url"
  echo "  -b   repo branch or ref (default 'master')"
  echo "  -u   name of the service run-as user"
  exit 0
}

while getopts r:u:c:n:h:b: opt; do
  case "$opt" in
    u)  user=$OPTARG;;
    h)  usage;;
    r)  repo=$OPTARG;;
    b)  branch=$OPTARG;;
    \?) usage;;
  esac
done

branch=${branch:-master}

if [[ -z "$user" || -z "$repo" ]]; then
  echo "missing required parameter"
  exit 1
fi

install-packages python-dev python-pip git-core python-setuptools gcc libc6-dev libxml2-dev libxslt-dev libz-dev
install-os-service "$user" "$repo" "$branch"
