#!/bin/sh -ex
# 2013 Marco B Caminati
# Script to put all wanted texlive collection containing map file fonts into one scm:
toinstall="collection-latexrecommended collection-latexextra collection-mathextra collection-metapost ulem collection-htmlxml"
# collection-fontsrecommended is depended on by collection-mathextra, -pictures by -latexextra.
# Using a tcz would require lots of symlinks upon loading it, and this wastes space! 
# scm is better, and we can adapt TDS through kpathsea configuration (see texlive.tcz's buildscript).
# TBD: Could be improved by further separating into a critical font scm (dvips, meta*, fonts, texmv-var) and a scm with the remaining bits.
# TBD: binaries here won't find a texmf.cnf
# loading only the latter would provide a reasonably complete environment with less TC extensions to download

[ $mtp ] || mtp=/mnt/iso; prefix=/tmp/pack; pkgname=texlive-fonts
mkdir "${mtp}" && sudo mount "${1}" "${mtp}"
prefix2=/tmp/pack2; pkgname2=texlive-recommended
chkext=.md5.txt; texmfroot="texmf-local"; varfig=.texlive2012; tc="$(cat /etc/sysconfig/tcuser)"
texmfvar="${varfig}/texmf-var"; texmfconfig="${varfig}/texmf-config"
sysprefix=/usr/local/texlive/2012
rm ${prefix} -r || true
sudo -u "${tc}" tce-load -i findutils.tcz perl5.tcz wget.tcz squashfs-tools-4.x.tcz 
sudo -u "${tc}" tce-load -ic texlive.tcz 
touch /tmp/mark && sudo tlmgr --repository "${mtp}" install $toinstall 
find /usr/local/texlive -cnewer /tmp/mark -not -type d | egrep -v "ls-R$" | cpio -d -p "${prefix}"
umount "${mtp}" && rmdir "${mtp}"
(cd ${prefix}/${sysprefix}/texmf-dist/ && rm -r ./doc ./source) || exit 12
(cd ${prefix} && mkdir -p "${texmfroot}") || exit 11
mv ${prefix}/${sysprefix}/texmf-dist/* ${prefix}/${texmfroot}/
# This should work as from the following comment in texmf.cnf:
# % TEXMFLOCAL follows TEXMFMAIN (and precedes TEXMFDIST)
(cd ${prefix} && ln -s "./${texmfroot}" "./texmf-dist") 
rmdir ${prefix}/${sysprefix}/texmf-dist/
mv "${prefix}/${sysprefix}/texmf-var/" "${prefix}/"
# mv "${prefix}/${sysprefix}/bin/" "${prefix}"
rmdir ${prefix}/${sysprefix}/ -p || true
mkdir ${prefix2}/${texmfroot} -p
(cd ${prefix}/${texmfroot} && mv bibtex tex ${prefix2}/${texmfroot})
mksquashfs "${prefix}" "${pkgname}.scm"
md5sum "${pkgname}.scm" > "${pkgname}.scm${chkext}"
mksquashfs "${prefix2}" "${pkgname2}.scm"
md5sum "${pkgname2}.scm" > "${pkgname2}.scm${chkext}"

# _texmfhome="${prefix}/${texmfhome}"
# _texmfvar="${prefix}/${texmfvar}"
# _texmfconfig="${prefix}/${texmfconfig}"
