#!/bin/sh -e

if [ $# -ne 1 ] ; then
  echo "Usage: `basename $0` CRAN_package_name"
  exit 1
fi

if [ "$1" = "splines" ] ; then
  echo "Package $1 already ships with r-base-core."
  exit 0
fi

if [ "$1" = "stats4" ] ; then
  echo "Package $1 already ships with r-base-core."
  exit 0
fi

do_wnpp_check () {
  retval=""
  wnpp=`wnpp-check $wnppname | sed 's/^(.* - #\([0-9]\+\)) http.*/\1/'`
  if [ "$wnpp" != "" ] ; then
    newversion=`PGPASSWORD="public-udd-mirror" psql --port=5432 --host=public-udd-mirror.xvm.mit.edu --username=public-udd-mirror -t udd -c "select version from new_packages where package = '$wnppname' ;"`
    if [ "$newversion" != "" ] ; then
      >&2 echo "Package $wnppname is just in Debian new queue waiting for processing"
      retval="new"
    else
      >&2 echo "Package $wnppname was ITPed in bug #$wnpp.  Please check http://bugs.debian.org/$wnpp"
      retval="$wnpp"
    fi
  fi
  echo $retval
}

workdir=`pwd`
cranname=$1
pkgname=r-cran-`echo $cranname | tr '[A-Z]' '[a-z]'`
if apt-cache policy $pkgname | grep -q unstable ; then
  echo "Package $pkgname is available in Debian unstable."
  exit 0
fi
wnppname=$pkgname
wnppcheck=$( do_wnpp_check )
if [ "$wnppcheck" = "new" ] ; then
  echo "No point to deal with a package which is in new - exitting"
  exit 0
else
  # If wnpp_check did not found r-cran-NAME try r-bioc
  if [ "$wnppcheck" = "" ] ; then
    wnppname="r-bioc-`echo $cranname | tr '[A-Z]' '[a-z]'`"
    wnppcheck=$( do_wnpp_check )
    if [ "$wnppcheck" = "new" ] ; then
      echo "No point to deal with a package which is in new - exitting"
      exit 0
    fi
  fi
fi
if echo $workdir | grep -q CRAN_prospective ; then
  basedir=`echo $workdir | sed 's#\(CRAN_prospective\).*#\1#'`
else
  basedir=`dirname $workdir`/CRAN_prospective
fi
targetdir="$basedir/$pkgname"

if [ -d `dirname ${targetdir}`/${cranname}/debian -o -d $targetdir ] ; then
  echo "Previous packaging attempt for $cranname exists in `dirname ${targetdir}`/${cranname}"
  exit 0
fi

mkdir -p $targetdir/debian
cd $targetdir

if [ "$DEBFULLNAME" != "" -a "$DEBEMAIL" != "" ] ; then
  AUTHOR="$DEBFULLNAME <${DEBEMAIL}>"
else
  AUTHOR="FIXME: DEBFULLNAME <DEBEMAIL> (you should set these variables in your environment)"
fi

cat > debian/changelog <<EOT
$pkgname (0.0-1) UNRELEASED; urgency=medium

  * Initial release

 -- $AUTHOR  `date -R`
EOT

cat > debian/watch <<EOT
version=4
https://cloud.r-project.org/src/contrib/${cranname}@ANY_VERSION@@ARCHIVE_EXT@
EOT

tarball=`uscan --verbose 2>/dev/null | grep ".orig.tar.[gx]z" | sed 's#^.* \(\.\./.*\.orig\.tar\.[gx]z\).*#\1#'`

BIOCDATA=""
if [ "$tarball" = "" ] ; then
  # if nothing was found on CRAN try BioConductor
  sed -i 's/^r-cran-/r-bioc-/' debian/changelog
  cat > debian/watch <<EOT
version=4
opts=downloadurlmangle=s?^(.*)\.\.?https://bioconductor.org/packages/release/bioc? \
 https://www.bioconductor.org/packages/release/bioc/html/${cranname}.html .*/${cranname}@ANY_VERSION@@ARCHIVE_EXT@
EOT
  tarball=`uscan --verbose 2>/dev/null | grep ".orig.tar.[gx]z" | sed 's#^.* \(\.\./.*\.orig\.tar\.[gx]z\).*#\1#'`
  if [ "$tarball" = "" ] ; then
    # There is a last resort chance to find the package in BioConductor data area
    cat > debian/watch <<EOT
version=4
opts=downloadurlmangle=s?^(.*)\.\.?http:\$1packages/release/data/experiment? \
 https://www.bioconductor.org/packages/release/data/experiment/html/${cranname}.html .*/${cranname}@ANY_VERSION@@ARCHIVE_EXT@
EOT
    tarball=`uscan --verbose 2>/dev/null | grep ".orig.tar.[gx]z" | sed 's#^.* \(\.\./.*\.orig\.tar\.[gx]z\).*#\1#'`
    if [ "$tarball" = "" ] ; then
      echo "$cranname was neither found on CRAN nor BioConductor nor BioConductor data"
      exit 1
    fi
    BIOCDATA="true"
    pkgname=r-bioc-`echo $cranname | tr '[A-Z]' '[a-z]'`
    cp -a debian/watch /tmp/watch_$pkgname
  fi
  pkgname=r-bioc-`echo $cranname | tr '[A-Z]' '[a-z]'`
fi

cd ..
rm -rf r-cran-`echo $cranname | tr '[A-Z]' '[a-z]'`
tarball=`echo $tarball | sed 's#^\.\./##'`
tar xaf $tarball
cd $cranname
if [ `find . -iname "test*" | wc -l` -gt 0 ] ; then
  dh-make-R --test run-unit-test 2>/dev/null >/dev/null
else
  dh-make-R 2>/dev/null >/dev/null
fi

# FIXME: dh-r does not know BioC data location yet.
#        This hack restores working watch file and hacks in proper Homepage
if [ "$BIOCDATA" = "true" -a -e /tmp/watch_$pkgname ] ; then
  mv /tmp/watch_$pkgname debian/watch
  # Fix Homepage
  sed -i 's+^\(Homepage.*.org/packages/\)+&data/experiment/+' debian/control
fi

# Hack to get cme formatted d/control
sed -i 's/^Standards-Version: .*/Standards-Version: 4.0.0/' debian/control
cme fix dpkg-control 2>/dev/null >/dev/null || true

if [ `find . -iname "*.rda" -o -iname "*.rdata" | wc -l` -gt 0 ] ; then
  cd debian
  /usr/share/dh-r/create_README.source > README.source
  cd ..
fi

cd ..
gitdir="$basedir/$pkgname"
mkdir $gitdir
cd $gitdir
git init
#newversion=`echo ../$tarball | sed 's/^.*_\([0-9].*\)\.orig\.tar\..*/\1/'`
#gbp import-orig --pristine-tar --upstream-version=$newversion ../$tarball
gbp import-orig --pristine-tar --no-interactive ../$tarball
mv ../$cranname/debian .
git add debian
git commit -a -m"Initial packaging by `basename $0`"
rm ../`readlink ../$tarball`
rm ../$tarball
rm -rf ../$cranname

if [ "$wnppcheck" != "" ] ; then
  echo "Please make sure you contact reporter of ITP bug $wnppcheck to sort out the status if the package"
  sed -i "/Initial release/s/xxxxxx/$wnppcheck/" debian/changelog
fi

echo "You can find a packaging repository for $cranname in `pwd`"
