#!/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)
		[ $with_option -eq 1 ] && \
		    echo "E: you only give one option" && return 1
		with_option=1
		;;
	    --help)
		Usage
		return 1
		;;
	    --minimal-collections|--standard-collections|--full-collections)
		[ ! -f /etc/vine-release ] && \
		    echo "E: support Vine Linux only" && return 1
		;;
	    *)
		[ -z "$(egrep -n "^name $1$" $TLPDB)" ] && \
		    echo "E: unknown option or package: $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=0
    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=1
	    [ $is_pkg -eq 0 ] && 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)"
    local i=

    tlpkg4a --filelist $pkg || return 1

    ## if $pkg is not collection-*, only return the filelist of $pkg
    echo $pkg | egrep -q "^collection-" || return 0

    ##!! 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)"
    local i=

    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
}

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

    ## search AddFormat, AddHypen
    tlpkg4a --execute $pkg | grep -e "Add"

    ##!! 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 "Add"
    done

    return 0
}

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

    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)

    ## 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

    PKG_SHORTDESC=$(tlpkg4a --shortdesc $pkg)
    PKG_LONGDESC=$(tlpkg4a --longdesc $pkg)

    PKG_CTANPKGSLIST=$(for i in $(tlpkg4a --depend $pkg); do \
	if [ -z "$(echo "$i" | grep "collection-")" ]; then \
            echo -n "$i: "; \
            tmp=$(tlpkg4a --shortdesc $i); \
            [ -z "${tmp}" ] && echo || echo "$tmp"; \
	fi
	done)

    PKG_MANIFEST=$(tlpkg2manifest $pkg)
    [ -z "${PKG_MANIFEST}" ] && \
	echo "W: empty manifest: $pkg" && return 1

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

    with_maplist=0
    MAPLIST="$(tlpkg2maplist $pkg)"
    [ ! -z "$MAPLIST" ] && with_maplist=1
    ##echo $with_maplist && echo "$MAPLIST" && exit

    with_inilist=0
    INILIST="$(tlpkg2inilist $pkg)"
    [ ! -z "$INILIST" ] && with_inilist=1
    ##echo $with_inilist && echo "$INILIST" && exit

cat<<EOF
## -*- coding: utf-8-unix -*-
## NOTE: This spec file is generated by $(basename $0) ${VERSION}-${RELEASE}: 
## $(basename $0) $pkg

%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}
Summary(ja): ${RPM_SUMMARY}
Name: texlive-$pkg
Version: ${VERSION}
Release: ${RELEASE}%{?_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 ${PKG_SHORTDESC}: 
${PKG_LONGDESC}

This package contains the following CTAN packages: 
${PKG_CTANPKGSLIST}

%description -l ja
TeX Live ソフトウェアディストリビューションは、
さまざまな Unix, Macintosh, Windows、および
他のプラットホームに対して完全な TeX システムを提供します。
多くの異なった言語を含む TeX ドキュメントの
編集、組版、閲覧、印刷するためのプログラム、
そして、TeX マクロやフォントライブラリの大きなコレクションを
同梱しています。

このディストリビューションは
同梱しているソフトウェアパッケージのためのドキュメントばかりでなく、
TeX に関するたくさんの一般的なドキュメントを含んでいます。

このパッケージは以下のようなパッケージ集です。
${PKG_SHORTDESC}: 
${PKG_LONGDESC}

このパッケージは以下の CTAN パッケージを含んでいます： 
${PKG_CTANPKGSLIST}

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=(
${PKG_MANIFEST}
)

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

## 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

## fix perl path
for i in source/metapost/expressg/expressg.dtx \\
         doc/metapost/expressg/n2mpsprl.prl \\
         doc/latex/songbook/contrib/crd2sb/crd2sb; do 
    [ -f %{build_texmf}-dist/\${i} ] && \\
        %__sed -i -e "s|^#!/usr/local/bin/perl|#!%{__perl}|" %{build_texmf}-dist/\${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 arch dependent binaries
%__rm -f %{build_texmf}-dist/source/latex/splitindex/splitindex-{OpenBSD,Linux}-i386

## 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}

EOF

## Running updmap
if [ $with_maplist -eq 1 ]; then
    cat<<EOF
[ -f %{texmf}/web2c/updmap.cfg ] || exit 0

updmap_lock=%{texmf}/updmap.lock
$(echo "$MAPLIST" | while read maptype map; do \
    cat<<EOT
%{exec_updmap} --listmaps 2>/dev/null | egrep -q "^#! ${maptype} ${map}" && \\
    echo -n "    " && \\
    echo -n "Running updmap: enable ${map} ... " && \\
    %{exec_updmap} --nomkmap --enable ${maptype} ${map} >/dev/null 2>&1 && \\
    echo "done." && \\
    touch \${updmap_lock}
EOT
done)

rpm -q --quiet texlive-common || exit 0

[ -f \${updmap_lock} ] && \\
    echo -n "    " && \\
    echo -n "Running updmap: recreate map files ... " && \\
    %{exec_updmap} >/dev/null 2>&1 && \\
    echo "done." && \\
    rm -f \${updmap_lock}

EOF
fi

## Running fmtutil
if [ $with_inilist -eq 1 ]; then
    cat<<EOF
rpm -q --quiet texlive-common || exit 0

echo -n "    "
echo -n "Running fmtutil ... " && %{exec_fmtutil} && echo "done."

EOF
fi

cat<<EOF
exit 0


%postun
if [ "\$1" = 0 ]; then
    %{exec_texhash}

EOF

## Running updmap
if [ $with_maplist -eq 1 ]; then
    cat<<EOF
    [ -f %{texmf}/web2c/updmap.cfg ] || exit 0

$(echo "$MAPLIST" | while read maptype map; do \
    cat<<EOT
    %{exec_updmap} --listmaps 2>/dev/null | egrep -q "^${maptype} ${map}" && \\
        echo -n "    " && \\
        echo -n "Running updmap: disable ${map} ... " && \\
        %{exec_updmap} --nomkmap --disable ${map} >/dev/null 2>&1 && \\
        echo "done."
EOT
done)
    echo -n "    " && \\
        echo -n "Running updmap: recreate map files ... " && \\
        %{exec_updmap} >/dev/null 2>&1 && \\
        echo "done."

EOF
fi

cat<<EOF
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 $*)
- improved %%post

* Fri Oct 01 2010 Munehiro Yamamoto <munepi@vinelinux.org> 2009-2
- generated by $(basename $0) 2009-2: $(basename $0) $(echo $*)
- removed arch dependent binaries (texlive-collection-latexextra)
- fixed perl path
- improved updmap process in %%post and %%postun

* Sat Aug 07 2010 Munehiro Yamamoto <munepi@vinelinux.org> 2009-1
- generated by $(basename $0) 2009-1: $(basename $0) $(echo $*)
EOF

    return 0
}

## mkrpmcollection [--minimal-collections|--standard-collections|--full-collections]
mkrpmcollection(){
    local category=$(echo $1 | sed -e "s/--\([a-z]*\)-collections/\1/")
    local category_pkglist=
    local i=

    case $category in 
	minimal|standard)
	    category_pkglist=$(grep -e "${category}," $CATEGORYLIST | sed -e "s/${category},//g" | sed -e "s/,$//g")
	    ;;
	full)
	    category_pkglist=$(Usage | egrep "^collection-")
	    ;;
	*)
	    echo "E: unknown category: $category"
	    return 1
	    ;;
    esac

    for i in ${category_pkglist}; do 
	mkrpmspec $i > texlive-${i}-vl.spec
	if [ $? -eq 1 ]; then 
	    echo "texlive-${i}-vl.spec: "
	    cat texlive-${i}-vl.spec
	    rm -f texlive-${i}-vl.spec
	    continue
	fi
	rpmbuild -ba texlive-${i}-vl.spec || return 1
    done

    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=3

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

    ## category of collection-*
    CATEGORYLIST=/usr/share/texlive-vtlpkg/category.list

    ## 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|--standard-collections|--full-collections)
	mkrpmcollection $1 || exit 1
	;;
    *)
	mkrpmspec $1 || exit 1
	;;
esac

exit

### end of file
