#!/bin/bash
# Script to make a curl .tcel extension from source
# Requires the compiletc.tce extension.
# License: The Curl license - http://curl.haxx.se/docs/copyright.html




NAME=curl
VERSION=7.18.2
DOWNLOAD=http://curl.haxx.se/download
SOURCE="$NAME"-"$VERSION".tar.bz2
MD5SUM=c389be5b0525276e58865956b7465562
TMPDIR=/mnt/hda2/"$NAME"
PKG="$TMPDIR"/pkg
DEV="$TMPDIR"/dev
LIST="$TMPDIR"/"$NAME".list
LIST1="$TMPDIR"/"$NAME".list1
SRCDIR=/tmp

download() {
	cd "$SRCDIR"
	if [ -e "$SOURCE" ]; then
	  if [ $(md5sum "$SOURCE" | cut -c1-32) != "$MD5SUM" ]; then
	    rm "$SOURCE"
	  fi
	fi
	if [ ! -e "$SOURCE" ]; then
	  wget "$DOWNLOAD"/"$SOURCE"
	fi
	if [ $(md5sum "$SOURCE" | cut -c1-32) = "$MD5SUM" ]; then
	  echo "md5sum passed."
	else
	  echo "Download failed. aborting"
	  exit 1;
	fi
}

build_source() {
	tar xjvf "$SRCDIR"/"$SOURCE" -C "$TMPDIR"
	cd "$TMPDIR"/"$NAME"-"$VERSION"

	./configure --prefix=/usr/local
	make
	make DESTDIR="$PKG" install
	
	cd "$PKG"
	find . | xargs file | grep "executable" | grep ELF | grep "not stripped" | cut -f 1 -d : | xargs strip --strip-unneeded 2> /dev/null
	find . | xargs file | grep "shared object" | grep ELF | grep "not stripped" | cut -f 1 -d : | xargs strip -g 2> /dev/null
	rm -r "$PKG"/usr/local/share
	mv "$PKG"/usr/local/lib/{*.a,*.la} "$DEV"/usr/local/lib/
	mv "$PKG"/usr/local/lib/pkgconfig "$DEV"/usr/local/lib/
	mv "$PKG"/usr/local/bin/curl-config "$DEV"/usr/local/bin/
	mv "$PKG"/usr/local/include "$DEV"/usr/local/
}

make_extension() {
	cd "$PKG"
	find . -not -type d > "$LIST"
	tar -T "$LIST" -czvf /home/tc/"$NAME"-"$VERSION".tcel
	cd "$DEV"
	find . -not -type d > "$LIST1"
	tar -T "$LIST1" -czvf /home/tc/"$NAME"-"$VERSION"-devs.tce
}

###################Main################

CFLAGS="-march=i486 -mtune=i686 -Os -pipe"
CXXFLAGS="-march=i486 -mtune=i686 -Os -pipe"
set -e


if [ -e "$TMPDIR" ]; then
    rm -rf "$TMPDIR" 
fi
mkdir -p "$PKG" &&
mkdir -p "$DEV"/usr/local/{bin,lib} &&
download &&
build_source &&
make_extension &&
echo "Done."