#!/bin/bash

appname=`echo $1 | sed 's|-|.|' | sed 's|\.spec$||'`
prjpage=http://pypi.python.org/pypi/$appname
urlprfx=http://pypi.python.org/packages/source/$(echo $appname | sed -r 's|^(.).*|\1|')/$appname
endings="(\\.tar\\.gz|\\.tgz|\\.tar\\.bz2|\\.tbz2|\\.zip)"
rematch=".*$urlprfx/$appname-([0-9.]+)$endings#md5=([0-9a-fA-F]{32}).*"

# Fetch the application's project page
# We'll use this to find the version, archive type and md5sum
tmpf=`mktemp`
if ! wget -q -O $tmpf $prjpage; then
    echo "Unable to find version!"
    rm -f $tmpf
    exit 1
fi

# Get the version, archive type and md5sum
vers=$(sed -n -r "s!$rematch!\1 \2 \3!p" $tmpf | sort -r -n | head -n1 | cut -d' ' -f1)
arch=$(sed -n -r "s!$rematch!\1 \2 \3!p" $tmpf | sort -r -n | head -n1 | cut -d' ' -f2)
hash=$(sed -n -r "s!$rematch!\1 \2 \3!p" $tmpf | sort -r -n | head -n1 | cut -d' ' -f3)
pkgf=${appname}-${vers}${arch}
rm -f $tmpf

# Download the actual source code
tmpd=`mktemp -d`
if ! wget -q -O ${tmpd}/$pkgf $urlprfx/$pkgf; then
	echo "Unable to download $urlprfx/$pkgf!"
	rm -rf $tmpd
	exit 1
fi
if [ `md5sum ${tmpd}/$pkgf | cut -d' ' -f1` != $hash ]; then
	echo "Tarball has invalid md5 sum!"
	rm -rf $tmpd
	exit 1
fi

# Extract the source code
case "$arch" in
	*gz)
		tar xzf ${tmpd}/$pkgf -C $tmpd
    	;;
	*bz2)
		tar xjf ${tmpd}/$pkgf -C $tmpd
    	;;
	*zip)
		unzip -qq ${tmpd}/$pkgf -d $tmpd
		;;
	*)
		echo "Invalid archive format!"
		rm -rf $tmpd
		exit 1
		;;
esac

# Fetch the summary and description fields and a list of all the requires
pkgi=$tmpd/${appname}-$vers/src/$appname.egg-info/PKG-INFO
preq=$tmpd/${appname}-$vers/src/$appname.egg-info/requires.txt
docs=`echo $(ls $tmpd/${appname}-$vers/ | grep "\.txt$")`
summ=$(sed -n -r 's!^Summary: (.*)$!\1!p' $pkgi)
dscr=$(awk '/^[ \t]*$/               { bl=bl + 1 }
            /^(Description:|[ \t]+)/ {
     	        if (bl < 2 && match($0, "^[ \t]*$") == 0) {
     		        sub("^(Description:[ \t]*|[ \t]*)", "");
     		        print $0;
                }
            }' $pkgi)

# Start building our spec file
tmpf=`mktemp`
awk '{ if (start) print $0; } /^@@START_OF_SPEC@@$/ { start=1; }' $0 > $tmpf

# Substitue a bunch of variables
sed -i -r "s|@MODNAME@|$appname|g" $tmpf
sed -i -r "s|@VERSION@|$vers|g" $tmpf
sed -i -r "s|@ARCHIVE@|$arch|g" $tmpf
sed -i -r "s|@SUMMARY@|$summ|g" $tmpf
sed -i -r "s|@DOCS@|$docs|g" $tmpf
sed -i -r "s|@DESCRIPTION@|$(echo $dscr)|g" $tmpf

# Generate our requires
awk '/^\[/ { stop=1; } { if (!stop && $0) print $0; }' $preq \
    | grep -v "^setuptools" \
	| sed -r 's!\.!-!' | sed -r 's!(.*)!python-\1!' \
    | while read req; do
          sed -i -r "s|^BuildRequires:( *)python-setuptools$|BuildRequires:\1python-setuptools\nRequires:     \1${req}|" $tmpf
      done

# Fix BuildArch if necessary
if find $tmpd | grep '\.c$'; then
    sed -i -r "s|^BuildArch: *noarch$||" $tmpf
fi

# Make sure that we have a wrapped description and a proper changelog
dashname=`echo $appname | sed 's!\.!-!'`
fold $tmpf -s > python-$dashname.spec
rpmdev-bumpspec python-$dashname.spec
rm -rf $tmpd $tmpf

exit 0
@@START_OF_SPEC@@
%{!?python_sitelib: %global python_sitelib %(%{__python} -c
    "from distutils.sysconfig import get_python_lib; print(get_python_lib())")}

%global modname @MODNAME@
%global fedranm %(echo %{modname} | sed -r 's|\\.|-|')
%global pathnam %(echo %{modname} | sed -r 's|\\.|/|')
%global frstltr %(echo %{modname} | sed -r 's|^(.).*|\\1|')

%global version @VERSION@
%global release 0

%global srcbase http://pypi.python.org/packages/source/%{frstltr}/%{modname}

Name:           python-%{fedranm}
Version:        %{version}
Release:        %{release}%{?dist}
Summary:        @SUMMARY@

Group:          Development/Libraries
License:        ZPLv2.1
URL:            http://pypi.python.org/pypi/%{modname}
Source0:        %{srcbase}/%{modname}-%{version}@ARCHIVE@
BuildRoot:      %{_tmppath}/%{name}-%{version}-%{release}-root-%(%{__id_u} -n)
BuildArch:      noarch

BuildRequires:  python-devel
BuildRequires:  python-setuptools

%description
@DESCRIPTION@

%prep
%setup -q -n %{modname}-%{version}

%build
%{__python} setup.py build

%install
rm -rf $RPM_BUILD_ROOT
%{__python} setup.py install -O1 --skip-build --root $RPM_BUILD_ROOT
 
%clean
rm -rf $RPM_BUILD_ROOT

%files
%defattr(-,root,root,-)
%doc @DOCS@
%{python_sitelib}/%{pathnam}
%{python_sitelib}/%{modname}-%{version}-*.egg-info
%{python_sitelib}/%{modname}-%{version}-*.pth

%changelog
