#! /bin/bash

MAGICFILEFILE="$0.magic.file"
MAGICOSFILE="$0.magic.os"
MAGICPLATFILE="$0.magic.platform"

OSNAME="`uname -s`"
CPUPLAT="`uname -m`"

if [ -f "${MAGICFILEFILE}" -a -f "${MAGICOSFILE}" -a -f "${MAGICPLATFILE}" ]; then
	MAGICPLAT="$(cat "${MAGICPLATFILE}")"
	MAGICOS="$(cat "${MAGICOSFILE}")"
	MAGICFILE="$(cat "${MAGICFILEFILE}" | dd conv=lcase 2>/dev/null)"

	case "${MAGICPLAT}" in
		unix)
			case "${MAGICFILE}" in
				*elf*x86-64*)
					CPUPLAT="x86_64"
					;;
				*elf*intel\ 80386*)
					CPUPLAT="ix86"
					;;
				*parisc*|*pa-risc*)
					CPUPLAT="parisc"
					;;
				*elf*32-bit*sparc*)
					CPUPLAT="sparc"
					;;
				*elf*64-bit*sparc*)
					CPUPLAT="sparc64"
					;;
			esac

			if [ "${MAGICOS}" != "`uname -s`" ]; then
				# Cross compiling, try to determine OS ...
				true
			fi
			;;
		win)
			if grep "64-bit" "${MAGICFILEFILE}" >/dev/null; then
				echo "win32-x86_64"
			else
				echo "win32-ix86"
			fi

			exit 0
			;;
		macosx)
			;;
	esac
fi

case "${OSNAME}" in
	Linux)
		GLIBCVERS=$(strings /lib/libc.so.6 | grep '^GLIBC_[0-9][0-9]*\.[0-9]*' | cut -f 2- -d _ | cut -f 1-2 -d . | sed 's@\.@ @g' |  sort -n +0 +1 | tail -1 | sed 's@ @\.@g')

		case "${CPUPLAT}" in
			i?86)
				CPUPLAT="ix86"
				;;
			sun4m)
				CPUPLAT="sparc"
				;;
		esac

		echo "linux-glibc${GLIBCVERS}-${CPUPLAT}"
		;;
	SunOS)
		SUNMAJVER=$(uname -r | cut -f 1 -d .)
		SUNMINVER=$(uname -r | cut -f 2 -d .)
		SOLVER="$[${SUNMAJVER} - 3].${SUNMINVER}"

		if [ -z "${CPUPLAT}" ]; then
			echo 'Unable to determine platform' >&2

			exit 1
		fi

		echo "solaris${SOLVER}-${CPUPLAT}"
		;;
	HP-UX)
		echo "hpux-${CPUPLAT}"
		;;
	*)
		if [ -z "${CPUPLAT}" ]; then
			CPUPLAT="`uname -m | dd conv=lcase 2>/dev/null`"
		fi

		echo "`uname -s | dd conv=lcase 2>/dev/null`-${CPUPLAT}"
		;;
esac
