#!/bin/bash

SNAPSHOT=false
while [ "`echo $1 |cut -b1`" = "-" ]; do
	case "$1" in
	-s|--snapshot)
		SNAPSHOT=true
		;;
	esac
	shift
done

NAME=`echo $1 |sed -e "s/\.spec$//"`
if echo $NAME |grep -q '^python-'; then
	PNAME="$NAME"
	NAME="`echo $NAME |cut -b8-`"
else
	PNAME="python-$NAME"
fi
[ -z "$EDITOR" ] && EDITOR="$VISUAL"
if [ -z "$EDITOR" ]; then
	if [ -e /usr/bin/vim ]; then
		EDITOR=/usr/bin/vim
	fi
fi
ID="`cat /etc/passwd |grep "^$(id -un):" |cut -d: -f5` <`id -un`@`hostname |cut -d. -f2-`>"
[ -e ~/.vs ] && source ~/.vs
[ -z "$ABFDIR" ] && ABFDIR=~/abf

curl https://pypi.org/pypi/$NAME/json >/tmp/$NAME.$$
if cat /tmp/$NAME.$$ |grep -q '"message": "Not Found"'; then
	rm /tmp/$NAME.$$
	NAME="python-$NAME"
	set -x
	curl https://pypi.org/pypi/$NAME/json >/tmp/$NAME.$$
fi
if [ -e /tmp/$NAME.$$ ]; then
	V=`cat /tmp/$NAME.$$ |python -c "import sys,json; print(json.load(sys.stdin)['info']['version']);"`
	S=`cat /tmp/$NAME.$$ |python -c "import sys,json; print(json.load(sys.stdin)['info']['summary']);"`
	# SS -- short summary (newlines killed)
	SS=`echo $S |xargs echo`
	L=`cat /tmp/$NAME.$$ |python -c "import sys,json; print(json.load(sys.stdin)['info']['license']);"`
	rm -f /tmp/$NAME.$$
fi
[ -z "$L" ] && L="GPL"

mkdir -p $ABFDIR/$PNAME
if [ ! -e $ABFDIR/$PNAME/$PNAME.spec ]; then
	if $SNAPSHOT; then
		cat >$ABFDIR/$PNAME/$PNAME.spec <<EOF
%define beta %{nil}
%define scmrev %{nil}

EOF
	fi
	cat >>$ABFDIR/$PNAME/$PNAME.spec <<EOF
Name:		$PNAME
Version:	$V
EOF

	if $SNAPSHOT; then
		cat >>$ABFDIR/$PNAME/$PNAME.spec <<EOF
%if "%{beta}" == ""
%if "%{scmrev}" == ""
Release:	1
Source0:	$NAME-%{version}.tar.xz
%else
Release:	0.%{scmrev}.1
Source0:	$NAME-%{scmrev}.tar.xz
%endif
%else
%if "%{scmrev}" == ""
Release:	0.%{beta}.1
Source0:	$NAME-%{version}%{beta}.tar.xz
%else
Release:	0.%{beta}.0.%{scmrev}.1
Source0:	$NAME-%{scmrev}.tar.xz
%endif
%endif
EOF
	else
		cat >>$ABFDIR/$PNAME/$PNAME.spec <<EOF
Release:	1
Source0:	https://files.pythonhosted.org/packages/source/$(echo $NAME |cut -b1)/$NAME/$NAME-%{version}.tar.gz
EOF
	fi

	cat >>$ABFDIR/$PNAME/$PNAME.spec <<EOF
Summary:	$SS
URL:		https://pypi.org/project/$NAME/
License:	$L
Group:		Development/Python
EOF
	cat >>$ABFDIR/$PNAME/$PNAME.spec <<EOF
BuildRequires:	python
BuildSystem:	python
BuildArch:	noarch

%description
$S

%files
%{py_sitedir}/$NAME
%{py_sitedir}/${NAME//-/_}-*.*-info
EOF
fi
exec "$EDITOR" "$ABFDIR/$PNAME/$PNAME".spec
