#!/bin/bash
# tlpdb2rpmspec
# 
# Copyright 2010 Munehiro Yamamoto <munepi@vinelinux.org>
# This file is licensed under the GNU General Public License version 2
# or any later version.

Usage(){
    cat<<EOF
Usage:	$(basename $0) [option] [pkgname]

This script generates a rpm spec file for CTAN and collection-* packages of TeX Live. 

Options:
	--name:			return [pkgname]
	--category:		return the category of [pkgname]
	--revision:		return the revision of [pkgname]
	--depend:		return dependencies of [pkgname]
	--shortdesc:		return the short description of [pkgname]
	--longdesc:		return the description of [pkgname]
	--execute:		return post processe of [pkgname]
	--catalogue-ctan:	return the locate of [pkgname]
	--catalogue-date:	return the last update of [pkgname]
	--catalogue-license:	return the license of [pkgname]
	--catalogue-version:	return the version of [pkgname]
	--filelist:		return the filelist of [pkgname]
	--help:			show this help

Supoort collections-* packages: 
$(egrep "^name collection-" $TLPDB | sed -e "s,name ,,g")
EOF
}

check-parameter(){
    [ -z "$*" ] && Usage && return 1

    while [ ! -z "$*" ]; do
	case $1 in
	    --name|--category|--revision|--depend|--shortdesc|--longdesc|--execute|--catalogue-ctan|--catalogue-date|--catalogue-license|--catalogue-version|--filelist|--minimal-collections|--full-collections)
		[ $with_option -eq 1 ] && \
		    echo "E: you only give one option" && return 1
		with_option=1
		;;
	    --help)
		Usage
		return 1
		;;
	    --*)
		echo "E: unknown option: $1"
		return 1
		;;
	esac
	shift
    done

    return 0
}


## tlpkg4a [--name|--category|--revision|--depend|--shortdesc|--longdesc|--execute|--catalogue-ctan|--catalogue-date|--catalogue-license|--catalogue-version|--filelist] [pkgname]
tlpkg4a(){
    [ $# -eq 2 ] || return 1
    local opt=$1
    local pkg=$2
    local fieldname=$(echo $opt | sed -e "s,--,,")

    ## check param
    case $opt in
	--name|--category|--revision|--depend|--shortdesc|--longdesc|--execute|--catalogue-ctan|--catalogue-date|--catalogue-license|--catalogue-version|--filelist)
	    ;;
	*)
	    echo "E: unknown option: $opt"
	    exit 1
	    ;;
    esac

    ## get the head line of $pkg record
    pkg_LINE=$(egrep -n "^name $pkg$" $TLPDB | cut -d":" -f 1)

    ## read tlpdb
    is_pkg=1
    tail -n $(( $TLPDB_MAXLINE - $pkg_LINE + 1 )) $TLPDB | \
	while read field; do
	    ## find the record of $pkg
	    echo "$field" | egrep -q "^name $pkg" && is_pkg=0
	    [ $is_pkg -eq 1 ] && continue
	    
	    ## return the values of its field name
	    if [ "$opt" = "--filelist" ]; then
	    ## NOTE: we only need texmf-dist directories
		echo "$field" | egrep "^texmf-dist" | \
		    sed -e "s, details=.*,," -e "s, language=.*,,"
	    else
		echo "$field" | egrep "^${fieldname} " | sed -e "s,${fieldname} ,,"
	    fi
	    
	    ## end of the record of $pkg
	    echo "$field" | egrep -q "^[[:blank:]]*$" && break
        done
    
    return 0
}

## tlpkg2speclicense [pkgname]
tlpkg2speclicense(){
    [ $# -eq 1 ] || return 1
    local pkg=$1

    case $(tlpkg4a --catalogue-license $pkg) in
	gpl3) echo "GPLv3+";;
	gpl2) echo "GPLv2+";;
	gpl) echo "GPL+";;
	lppl|lppl1.2|lppl1.3) echo "LPPL";;
	other-free) echo "Freely redistributable without restriction";;
	pd) echo "Public Domain";;
	noinfo) echo "No Info";;
	lgpl) echo "LGPLv2+";;
	gfsl) echo "LPPL";;
	bsd) echo "BSD";;
	knuth) echo "Knuth";;
	unknown) echo "Unknown";;
	gfl) echo "LPPL";;
	artistic2) echo "Artistic 2.0";;
	fdl) echo "GFDL";;
	collection) echo "Public Domain";;
	artistic) echo "Artistic";;
	other) echo "Other";;
	ofl) echo "OFSFLD";;
	apache2) echo "ASL 2.0";;
	nosource) echo "No Source";;
	nosell) echo "No Sell";;
	nocommercial) echo "Non-commercial";;
	*) return 1;;
    esac
    return 0
}

## tlpkg2manifest [pkgname]
tlpkg2manifest(){
    [ $# -eq 1 ] || return 1
    local pkg=$1
    local pkgdeps="$(tlpkg4a --depend $pkg)"

    tlpkg4a --filelist $pkg || return 1

    ##!! we need pure filelist of $pkg; remove collection-*
    pkgdeps=$(echo $pkgdeps | sed -e "s,collection-[-A-Za-z0-9]*,,g")

    [ -z "$pkgdeps" ] && return 0
    for i in $pkgdeps; do 
    	tlpkg4a --filelist $i || return 1 
    done

    return 0
}

## tlpkg2maplist [pkgname]
tlpkg2maplist(){
    [ $# -eq 1 ] || return 1
    local pkg=$1
    local pkgdeps="$(tlpkg4a --depend $pkg)"

    tlpkg4a --execute $pkg | grep -e "Map" | sed -e "s,^add,,g"

    ##!! we need pure filelist of $pkg; remove collection-*
    pkgdeps=$(echo $pkgdeps | sed -e "s,collection-[-A-Za-z0-9]*,,g")

    [ -z "$pkgdeps" ] && return 0
    for i in $pkgdeps; do 
    	tlpkg4a --execute $i | grep -e "Map" | sed -e "s,^add,,g"
    done

    return 0
}


## mkrpmspec [pkgname]
mkrpmspec(){
    [ $# -eq 1 ] || return 1
    local pkg=$1

    RPM_SUMMARY="TeX Live: $(tlpkg4a --shortdesc $pkg)"

    ## Requires tag for texlive
    RPM_REQUIRES=$(for i in $(tlpkg4a --depend $pkg | egrep "^collection-" | egrep -v "^collection-documentation"); do echo "Requires: texlive-$i = %{version}"; done)
    ## collection-langgerman and collection-langcyrillic 
    ## need to complete fmtutil-sys on texlive + texlive-common
    [ "$pkg" = "collection-basic" ] && 
    RPM_REQUIRES="${RPM_REQUIRES}
Requires: texlive-collection-langgerman = %{version}
Requires: texlive-collection-langcyrillic = %{version}"

    ## License tag
    RPM_LICENSE="$(tlpkg2speclicense $pkg),"
    for i in $(tlpkg4a --depend $pkg | egrep -v "^collection-"); do 
	tmp=$(tlpkg2speclicense $i)
	echo "$RPM_LICENSE" | grep -q "${tmp},"
	[ $? -eq 1 ] && RPM_LICENSE="${RPM_LICENSE} ${tmp},"
    done
    RPM_LICENSE=$(echo "$RPM_LICENSE" | sed -e "s/,$//" | sed -e "s/^, //")
    [ -z "$RPM_LICENSE" ] && RPM_LICENSE=distributable

    with_docpkg=0
    [ -z "$(echo $pkg | grep "collection-documentation")" ] && \
	[ ! -z "$(tlpkg2manifest $pkg | grep texmf-dist/doc/)" ] && \
	with_docpkg=1

cat<<EOF
## -*- coding: utf-8-unix -*-
## NOTE: This spec file is generated by tlpdb2rpmspec.sh ${VERSION}-${RELEASE}: 
## tlpdb2rpmspec.sh collection-basic

%bcond_with firstbuild

%define tex_destdir	%{_datadir}
%define texmf		%{tex_destdir}/texmf
%define texlive_src	%{tex_destdir}/texlive-sources
%define build_tex_destdir	%{buildroot}%{tex_destdir}
%define build_texmf	%{buildroot}%{texmf}

%define exec_mktexlsr  [ -x %{_bindir}/texconfig-sys ] && PATH=%{_bindir}:\$PATH %{_bindir}/texconfig-sys rehash
%define exec_texhash  [ -x %{_bindir}/texhash ] && PATH=%{_bindir}:\$PATH %{_bindir}/texhash
%define exec_updmap   [ -x %{_bindir}/updmap-sys ] && PATH=%{_bindir}:\$PATH %{_bindir}/updmap-sys --nostop
%define exec_fmtutil  [ -x %{_bindir}/fmtutil-sys ] && PATH=%{_bindir}:\$PATH %{_bindir}/fmtutil-sys --all >/dev/null 2>&1
%define exec_upddeffont    [ -x %{_sbindir}/update-defaultfont ] && %{_sbindir}/update-defaultfont 2> /dev/null
%define vartexfonts %{_var}/lib/texmf

%define __find_provides	%{nil}
%define __find_requires	%{nil}
%define __perl_provides %{nil}
%define __perl_requires %{nil}

Autoreq: 0

Summary: ${RPM_SUMMARY}
Name: texlive-$pkg
Version: ${VERSION}
Release: 1%{?_dist_release}
License: ${RPM_LICENSE}
Group: Applications/Publishing
URL:http://www.tug.org/texlive/

Requires: texlive = %{version}
$RPM_REQUIRES

Requires(post):		texlive = %{version}
Requires(postun):	texlive = %{version}
BuildRequires:		texlive-sources = %{version}

BuildArch:	noarch
Buildroot:	%{_tmppath}/%{name}-%{version}-root

Vendor:		${RPM_VENDOR}
Distribution:	${RPM_DISTRIBUTION}
Packager:	${RPM_PACKAGER}

%description
The TeX Live software distribution offers a complete TeX system for a
variety of Unix, Macintosh, Windows and other platforms. It
encompasses programs for editing, typesetting, previewing and printing
of TeX documents in many different languages, and a large collection
of TeX macros and font libraries.

The distribution includes extensive general documentation about TeX,
as well as the documentation for the included software packages.

This package is a collection of $(tlpkg4a --shortdesc $pkg): 
$(tlpkg4a --longdesc $pkg)

This package contains the following CTAN packages: 
$(for i in $(tlpkg4a --depend $pkg); do [ -z "$(echo "$i" | grep "collection-")" ] && echo -n "$i: " && tlpkg4a --shortdesc $i; done)

EOF

## subpackage: %{name}-doc
if [ $with_docpkg -eq 1 ]; then
    cat<<EOF
%package doc
Summary: TeX Live: Documentation files of %{name}
Group: Applications/Publishing
Requires: %{name} = %{version}-%{release}

%description doc
This package contains documentation files of %{name}.

EOF
fi

cat<<EOF
%prep

%build

%install
[ -n "%{buildroot}" -a "%{buildroot}" != / ] && %__rm -rf %{buildroot}

PREF=%{buildroot}%{tex_destdir}

manifest=(
$(tlpkg2manifest $pkg)
)

%__mkdir_p \${PREF}/texmf-dist
for i in "\${manifest[@]}"; do 
    %__install -D %{texlive_src}/\$i \${PREF}/\$i
done

## customize updmap.cfg for each font's map files
## copy as updmap-%{name}.maplist
%__rm -f updmap-%{name}.maplist
cat > updmap-%{name}.maplist<<EOT
$(tlpkg2maplist $pkg)
EOT
## NOTE: if the size of updmap-%{name}.maplist equals 1, 
## this only contains "\n". 
if [ \$(du -b updmap-%{name}.maplist | cut -f 1) -ne 1 ]; then
    %__mkdir_p %{build_texmf}/web2c/
    %__cp updmap-%{name}.maplist %{build_texmf}/web2c/updmap-%{name}.maplist
fi

## check ini files
if [ ! -z "\$(find %{buildroot} -name "*.ini")" ]; then
    %__mkdir_p %{build_texmf}/web2c/
    find %{buildroot} -name "*.ini" | %__sed -e "s,%{buildroot},,g" > %{build_texmf}/web2c/fmtutil-%{name}.inilist
fi

## info
%__rm -f %{buildroot}%{_infodir}/dir
%__gzip -9nf %{buildroot}%{_infodir}/*info* ||:

## man
## man t1* files are provided by t1utils
for i in t1ascii t1asm t1binary t1disasm t1mac t1unmac; do
    %__rm %{buildroot}%{_mandir}/man*/\${i}.* ||:
done

## man some files are provided by psutils
for i in epsffit extractres fixdlsrps fixfmps fixmacps fixpsditps fixpspps fixscribeps fixtpps fixwfwps fixwpps fixwwps getafm includeres psbook psmerge psnup psresize psselect pstops; do
    %__rm %{buildroot}%{_mandir}/man*/\${i}.* ||:
done

## remove asymptote directries, which provides asymptote package
find %{buildroot} -regex ".*asymptote.*" | xargs %__rm -rf
# find %{buildroot} -name "Makefile" | xargs %__rm -f

# ## remove xindy
# find %{buildroot} -regex ".*xindy.*" | xargs %__rm -rf

# ## remove tex4ht
# find %{buildroot} -regex ".*tex4ht.*" | xargs %__rm -rf

## remove unpackaging files
find %{buildroot} | %__grep -e "\\.\(la\|a\)\$" | xargs %__rm -f
find %{buildroot} | %__grep -e "\\.\(diff\|patch\)\$" | xargs %__rm -f

## Files list
find %{buildroot} -type f -or -type l | \\
    %__sed -e "s|%{buildroot}||g" > filelist.full

find %{buildroot}%{texmf}-dist -type d | \\
    %__sed -e "s|^%{buildroot}|%dir |" \\
           -e "s|\$|/|"             >> filelist.full

EOF

## subpackage: %{name}-doc
if [ $with_docpkg -eq 1 ]; then
    cat<<EOF
## subpackages
grep "/texmf-dist/doc/" filelist.full > filelist.doc
cat filelist.doc filelist.full | sort | uniq -u > filelist.tmp
%__mv -f filelist.tmp filelist.full

EOF
fi

cat<<EOF
%clean
%__rm -rf %{buildroot}

%post
%{exec_texhash}
[ -x %{_bindir}/updmap-sys ] || exit 0
[ -f %{texmf}/web2c/updmap.cfg ] || exit 0
if [ -f %{texmf}/web2c/updmap-%{name}.maplist ]; then
    while read maptype map; do
	%{exec_updmap} --listmaps 2>/dev/null | egrep -q "^\${maptype} \${map}"
	[ \$? -eq 0 ] && continue
	echo -n "    "
	echo -n "Running updmap: enable \${map} ... "
	%{exec_updmap} --enable \${maptype} \${map} >/dev/null 2>&1
	echo "done."
    done < %{texmf}/web2c/updmap-%{name}.maplist
fi

if [ -f %{texmf}/web2c/fmtutil-%{name}.inilist ]; then
    echo -n "    "
    echo -n "Running fmtutil ... " && %{exec_fmtutil} && echo "done."
fi

exit 0


%postun
if [ "\$1" = 0 ]; then
    %{exec_texhash}
    [ -x %{_bindir}/updmap-sys ] || exit 0
    [ -f %{texmf}/web2c/updmap.cfg ] || exit 0
    if [ -f %{texmf}/web2c/updmap-%{name}.maplist ]; then
	while read maptype map; do
	    %{exec_updmap} --listmaps 2>/dev/null | egrep -q "#! ^\${maptype} \${map}"
	    [ \$? -eq 0 ] && continue
	    echo -n "    "
	    echo -n "disable \${map} ... "
	    %{exec_updmap} --disable \${map} >/dev/null 2>&1
	    echo "done."
	done < %{texmf}/web2c/updmap-%{name}.maplist
    fi
fi

exit 0

%files -f filelist.full
%defattr(-,root,root)

EOF

## subpackage: %{name}-doc
if [ $with_docpkg -eq 1 ]; then
    cat<<EOF
%files -f filelist.doc doc
%defattr(-,root,root)

EOF
fi

cat<<EOF
%changelog
* $(LANG=C date +%a) $(LANG=C date +%b) $(date +%d) $(date +%Y) ${RPM_GPG_NAME} ${VERSION}-${RELEASE}
- generated by $(basename $0) ${VERSION}-${RELEASE}: $(basename $0) $(echo $*)
EOF

    return 0
}

setup-tlpdb2rpmspec(){
    ## load your .vtlpkg.conf
    if [ -f ${HOME}/.vtlpkg.conf ]; then
	. ${HOME}/.vtlpkg.conf
    else
	echo "E: ${HOME}/.vtlpkg.conf: No such file"
	return 1
    fi

    [ -z "$RPM_VENDOR" ] && \
	echo "E: \$RPM_VENDOR is empty" && exit 1
    [ -z "$RPM_DISTRIBUTION" ] && \
	echo "E: \$RPM_DISTRIBUTION is empty" && exit 1
    [ -z "$RPM_GPG_NAME" ] && \
	echo "E: \$RPM_GPG_NAME is empty" && exit 1
    [ -z "$RPM_PACKAGER" ] && \
	echo "E: \$RPM_PACKAGER is empty" && exit 1

    ## setup configurations
    VERSION=2009
    RELEASE=1

    ## set a tlpdb file for TeX Live, which is a package database file. 
    TLPDB=/usr/share/texlive-sources/tlpkg/texlive.tlpdb
    TLPDB_MAXLINE=$(wc -l $TLPDB | cut -d" " -f 1)

    ## set some booleans
    with_option=0
}

##############################################################################

setup-tlpdb2rpmspec || exit 1

check-parameter $* || exit 1

case $1 in
    --name|--category|--revision|--depend|--shortdesc|--longdesc|--execute|--catalogue-ctan|--catalogue-date|--catalogue-license|--catalogue-version|--filelist)
	tlpkg4a $1 $2 || exit 1
	;;
    --minimal-collections)
	[ ! -f /etc/vine-release ] && echo "E: support Vine Linux only" && exit 1
	## minimal installation needs to build texlive (secondbuild)
	for i in collection-langgerman \
	         collection-langcyrillic \
	         collection-xetex \
	         collection-latexrecommended \
	         collection-latex \
	         collection-fontsrecommended \
	         collection-basic; do 
	    $0 $i > texlive-${i}-vl.spec
	    rpmbuild -ba texlive-${i}-vl.spec || exit 1
	done
	;;
    --standard-collections)
	[ ! -f /etc/vine-release ] && echo "E: support Vine Linux only" && exit 1
	for i in collection-bibtexextra \
	    collection-context \
	    collection-latexextra \
	    collection-luatex \
	    collection-pictures \
	    collection-genericrecommended \
	    collection-pstricks \
	    collection-documentation-english; do 
	    $0 $i > texlive-${i}-vl.spec
	    rpmbuild -ba texlive-${i}-vl.spec || exit 1
	done
	;;
    --full-collections)
	[ ! -f /etc/vine-release ] && echo "E: support Vine Linux only" && exit 1
	for i in $(tlpdb2rpmspec.sh | egrep "^collection-"); do 
	    $0 $i > texlive-${i}-vl.spec
	    rpmbuild -ba texlive-${i}-vl.spec || exit 1
	done
	;;
    *)
	mkrpmspec $1 || exit 1
	;;
esac

exit

### end of file
