#!/bin/bash
#
# unzip vim-master and rename directory to gvim-master
# unzip vim-master again so there will be two directories
# because we need two builds, one with X (gvim) and one without (vim)
# run this script from the common parent of the two

EXT=gvim
TCZ=/tmp/$EXT/TCZ

sudo rm -rf /tmp/$EXT
SHDIR=$(pwd)

for a in compiletc bash file squashfs-tools \
		gettext fontconfig-dev libXft-dev xorg-server-dev Xorg-7.7-dev gtk3-dev
	do tce-load -i $a
done

export CC="gcc -mtune=generic -Os -pipe"
export CXX="g++ -mtune=generic -Os -pipe -fno-exceptions" 

cd $SHDIR/vim-master
rm src/auto/config.cache
./configure \
	--prefix=/usr/local \
	--sysconfdir=/usr/local/etc \
	--localstatedir=/var \
	--mandir=/usr/local/share/man \
	--without-x \
	--enable-gui=no \
	--enable-multibyte \
	|| exit

make || exit
make install DESTDIR=$TCZ-vim || exit
for a in $(find $TCZ-vim -type f); do file -b $a | grep -q '^ELF .*not stripped$' && strip $a; done

cd $SHDIR/gvim-master
rm src/auto/config.cache
./configure \
	--prefix=/usr/local \
	--sysconfdir=/usr/local/etc \
	--localstatedir=/var \
	--mandir=/usr/local/share/man \
	--with-x \
	--enable-gui=gtk3 \
	--enable-multibyte \
	|| exit

make || exit
make install DESTDIR=$TCZ-gvim || exit
for a in $(find $TCZ-gvim -type f); do file -b $a | grep -q '^ELF .*not stripped$' && strip $a; done

mkdir -p $TCZ-base/usr/local/
mv $TCZ-vim/usr/local/share $TCZ-base/usr/local

for a in $(diff -r $TCZ-gvim/usr/local/share $TCZ-base/usr/local/share \
		| grep "^Only in $TCZ-gvim" | sed -e 's#Only in ##' -e 's#: #/#')
	do b=$(echo $a | sed 's#TCZ-gvim#TCZ-base#')
	mkdir -p $(dirname $b)
	mv -f $a $b
done

rm -rf $TCZ-gvim/usr/local/share

mkdir -p $TCZ-doc/usr/local/share/vim/vim80
mv $TCZ-base/usr/local/share/vim/vim80/doc $TCZ-doc/usr/local/share/vim/vim80
mv $TCZ-base/usr/local/share/man $TCZ-doc/usr/local/share

mkdir -p $TCZ-tutor/usr/local/share/vim/vim80
mv $TCZ-base/usr/local/share/vim/vim80/tutor $TCZ-tutor/usr/local/share/vim/vim80
for a in $(find $TCZ-doc/usr/local -type f -name '*tutor*')
	do b=$(echo $a | sed 's#TCZ-doc#TCZ-tutor#')
	mkdir -p $(dirname $b)
	mv -f $a $b
done
for a in $(find $TCZ-vim/usr/local -type f -name '*tutor*')
	do b=$(echo $a | sed 's#TCZ-vim#TCZ-tutor#')
	mkdir -p $(dirname $b)
	mv -f $a $b
done
for a in $(find $TCZ-gvim/usr/local -type f -name '*tutor*')
	do b=$(echo $a | sed 's#TCZ-gvim#TCZ-tutor#')
	mkdir -p $(dirname $b)
	mv -f $a $b
done

sudo chown -R root.root $TCZ*

mksquashfs $TCZ-vim /tmp/$EXT/vim.tcz -noappend
mksquashfs $TCZ-gvim /tmp/$EXT/gvim.tcz -noappend
mksquashfs $TCZ-base /tmp/$EXT/gvim-base.tcz -noappend
mksquashfs $TCZ-doc /tmp/$EXT/gvim-doc.tcz -noappend
mksquashfs $TCZ-tutor /tmp/$EXT/gvim-tutor.tcz -noappend

