#!/bin/bash

# official repository / репозиторий официальной Psi
GIT_REPO_PSI=git://git.psi-im.org/psi.git

# do svn up on patches / обновлять патчи из svn
FORCE_PATCH_UPDATE=${FORCE_PATCH_UPDATE:-1}

# skip patches which applies with errors / пропускать глючные патчи
SKIP_INVALID_PATCH=${SKIP_INVALID_PATCH:-0}

# do git pull on psi git working copy on start
# обновляться с репозитория перед сборкой
FORCE_REPO_UPDATE=${FORCE_REPO_UPDATE:-1}

# log of applying patches / лог применения патчей
PATCH_LOG=${PATCH_LOG:-/dev/null}

# configure options / опции скрипта configure
CONF_OPTS="${CONF_OPTS:---prefix=/usr}"

# icons for downloads / иконки для скачивания
ICONSETS="${ICONSETS:-system clients activities moods}"

if [ "`uname`" = "FreeBSD" ]; then
	MAKEOPT=${MAKEOPT:--j$((`sysctl -n hw.ncpu`+1))}
	PATCH_DRYRUN_ARG="-C"
	STAT_FORMAT_ARG="-f"
else
	MAKEOPT=${MAKEOPT:--j$((`cat /proc/cpuinfo | grep processor | wc -l`+1))}
	PATCH_DRYRUN_ARG="--dry-run"
	STAT_FORMAT_ARG="-c"
fi
#######################
# FUNCTIONS / ФУНКЦИИ #
#######################
# Exit with error message
die() { echo; echo " !!!ERROR: ${1}"; exit 1; }

#smart patcher
spatch() {
  popts=""
  PATCH_TARGET="${1}"

  echo -n " * applying ${PATCH_TARGET}..." | tee -a $PATCH_LOG

  if (patch -p1 ${popts} ${PATCH_DRYRUN_ARG} -i ${PATCH_TARGET}) >> $PATCH_LOG 2>&1
  then
    if (patch -p1 ${popts} -i ${PATCH_TARGET} >> $PATCH_LOG 2>&1)
    then
    	echo " done" | tee -a $PATCH_LOG
	return 0
    else
    	echo "dry-run ok, but actual failed" | tee -a $PATCH_LOG
    fi
  else
    echo "failed" | tee -a $PATCH_LOG
  fi
  return 1
}

check_env() {
  echo -n "Testing environment.. "
  v=`git --version 2>/dev/null` || die "You should install Git first. / Сначала установите Git"
  v=`svn --version 2>/dev/null` || die "You should install subversion first. / Сначала установите subversion"
  v=`gmake --version 2>/dev/null`
  MAKE="gmake"
  if [ -z "$v" ]; then
    echo "gmake not found! / gmake не найден!"
    echo -n "trying just make / пробуем просто make.."
    v=`make --version 2>/dev/null`
    MAKE="make"
  fi
  [ ! -z "$v" ] || die "You should install GNU Make first / Сначала установите GNU Make"
  for qc in qt-qconf qconf; do
    v=`$qc --version 2>/dev/null |grep affinix` && QCONF=$qc
  done
  [ -z "${QCONF}" ] && die "You should install qconf(http://delta.affinix.com/qconf/) / Сначала установите qconf"
  echo "OK"
}

prepare_workspace() {
  echo -n "Init directories.. "
  if [ ! -d "${PSI_DIR}" ]
  then
    mkdir "${PSI_DIR}" || die "can't create work directory ${PSI_DIR}"
  fi
  rm -rf "${PSI_DIR}"/build
  [ -d "${PSI_DIR}"/build ] && die "can't delete old build directory ${PSI_DIR}/build"
  mkdir "${PSI_DIR}"/build || die "can't create build directory ${PSI_DIR}/build"
  echo "OK"
}

fetch_sources() {
  cd "${PSI_DIR}"
  if [ -d "git/.git" ]
  then
    echo "Starting updating.."
    cd git
    if [ $FORCE_REPO_UPDATE != 0 ]; then
      git pull || die "git update failed"
      git submodule init # just in case
    else
      echo "Update disabled in options"
    fi
  else
    echo "New fresh repo.."
    git clone "${GIT_REPO_PSI}" git || die "git clone failed"
    cd git
    git submodule init
  fi
  git submodule update || die "git submodule update failed"

  echo "downloading patches.."
  cd "${PSI_DIR}"
  if [ -d patches ]
  then
    [ $FORCE_PATCH_UPDATE != 0 ] && ( svn up patches || die "patches update failed" )
  else
    svn co http://psi-dev.googlecode.com/svn/trunk/patches/ patches \
  	|| die "patches checkout failed"
  fi

  if [ ! -d iconsets ]; then
    mkdir iconsets
  fi
  cd iconsets/

  for name in ${ICONSETS}; do
    if [ -d $name ]; then
      echo "Update $name icons..."
      svn up $name || die "$name icons update failed"
    else
      echo "Downloading $name iconset.."
      svn co "http://psi-dev.googlecode.com/svn/trunk/iconsets/$name/default" $name \
      || die "$name icons checkout failed"
    fi
  done

  cd "${PSI_DIR}"
}

prepare_sources() {
  echo "Exporting sources"
  cd "${PSI_DIR}"/git
  git archive --format=tar HEAD | ( cd "${PSI_DIR}/build" ; tar xf - )
  (
    export ddir="${PSI_DIR}/build"
    git submodule foreach '( git archive --format=tar HEAD ) \
    	| ( cd "${ddir}/${path}" ; tar xf - )'
  )

  cd "${PSI_DIR}"
  rev=`svnversion patches`
  rm patches/*win32* 2>/dev/null
  rm patches/*psi-dirty-check.diff 2>/dev/null
  PATCHES=`ls -1 patches/*diff 2>/dev/null`
  cd "${PSI_DIR}/build"
  for p in $PATCHES; do
     spatch "${PSI_DIR}/${p}"
     if [ "$?" != 0 ]
     then
       [ $SKIP_INVALID_PATCH != 0 ] && echo "skip invalid patch"
       [ $SKIP_INVALID_PATCH == 0 ] && die "can't continue due to patch failed"
     fi
  done
  sed "s/.xxx/.${rev}/" -i src/applicationinfo.cpp

  # prepare icons
  for name in ${ICONSETS}; do
	if [ ! -d ${PSI_DIR}/build/iconsets/$name ]
	then
		mkdir "${PSI_DIR}/build/iconsets/$name"
	fi
	svn export "${PSI_DIR}/iconsets/$name" "${PSI_DIR}/build/iconsets/$name/default" --force
  done

}

src_compile() {
  $QCONF
  ./configure ${CONF_OPTS} || die "configure failed"
  $MAKE $MAKEOPT || die "make failed"
}

pkg_install() {
  echo "Installing. it may require to enter password of owner of install directory.."
  if [ `stat $STAT_FORMAT_ARG "%u" "${INSTALL_ROOT}"` = $UID ]
  then
    $MAKE INSTALL_ROOT="${INSTALL_ROOT}" install || die "make install failed"
  else
    su -c "$MAKE INSTALL_ROOT=\"${INSTALL_ROOT}\" install" `stat $STAT_FORMAT_ARG "%U" "${INSTALL_ROOT}"` || die "make install failed"
  fi
}
