#!/bin/bash


# general settings

CC=gcc
LD=gcc


# usage

function usage()
{
  echo 
  echo "Usage: $(basename $0) TARGET"
  echo
  echo "  Supported targets are:"
  echo
  echo "    x86-linux    x86_64-linux"
  echo "    x86-darwin   x86_64-darwin"
  echo "    x86-windows  x86_64-windows"
  echo "    x86-cygwin"
  echo
  exit 1
}

# setup

[ "$#" -eq 0 ] && { echo "Error: missing target."; usage; }

target=$1

case "$target" in
  x86-linux)
    CFLAGS="-fPIC -I. -m32"
    LDFLAGS="-fPIC -m32 -shared"
    library="$target/libsha1.so"
    test_sha1="test_sha1"
    ;;
  x86_64-linux)
    CFLAGS="-fPIC -I. -m64"
    LDFLAGS="-fPIC -m64 -shared"
    library="$target/libsha1.so"
    test_sha1="test_sha1"
    ;;
  x86-darwin)
    LD=libtool
    CFLAGS="-fPIC -I. -m32"
    LDFLAGS="-dynamic -lc"
    library="$target/libsha1.so"
    test_sha1="test_sha1"
    ;;
  x86_64-darwin)
    LD=libtool
    CFLAGS="-fPIC -I. -m64"
    LDFLAGS="-dynamic -lc"
    library="$target/libsha1.so"
    test_sha1="test_sha1"
    ;;
  x86-cygwin)
    CFLAGS="-I. -m32"
    LDFLAGS="-shared"
    library="$target/sha1.dll"
    test_sha1="test_sha1.exe"
    ;;
  x86-windows)
    PATH="/mingw32/bin:$PATH"
    CFLAGS="-I. -m32"
    LDFLAGS="-shared"
    library="$target/sha1.dll"
    test_sha1="test_sha1.exe"
    ;;
  x86_64-windows)
    PATH="/mingw64/bin:$PATH"
    CFLAGS="-I. -m64"
    LDFLAGS="-shared"
    library="$target/sha1.dll"
    test_sha1="test_sha1.exe"
    ;;
  *)
    echo "Error: unsupported target: '$target'"
    usage
    ;;
esac


# building

[ -d "$target" ] || { mkdir $target; }

echo "Compiling library ..."
$CC $CFLAGS -c -o sha1.o sha1.c
[ "$?" -ne 0 ] && { exit 1; }

echo "Linking library ..."
$LD $LDFLAGS -o $library sha1.o
[ "$?" -ne 0 ] && { exit 1; }


# testing

if [ "$target" != x86-windows -a "$target" != x86_64-windows ]; then

echo "Building tests ..."
$CC $CFLAGS -o $test_sha1 test_sha1.c -ldl
[ "$?" -ne 0 ] && { exit 1; }

echo "Running tests ..."
./$test_sha1 $library
[ "$?" -ne 0 ] && { exit 1; }

rm test_sha1 sha1.o

fi