#!/bin/bash
#
# This file and its contents are supplied under the terms of the
# Common Development and Distribution License ("CDDL"), version 1.0.
# You may only use this file in accordance with the terms of version
# 1.0 of the CDDL.
#
# A full copy of the text of the CDDL should have accompanied this
# source.  A copy of the CDDL is also available via the Internet at
# http://www.illumos.org/license/CDDL.
#
# Copyright (c) 2014 by Delphix. All rights reserved.
# Copyright 2014 OmniTI Computer Consulting, Inc. All rights reserved.
#

function die
{
	echo "failed: $1" >&2
	exit 1
}

# Set CODEMGR_WS.
if [[ -z "$1" ]]; then
	export CODEMGR_WS=`git rev-parse --show-toplevel`
	if [[ -z "$CODEMGR_WS" ]]; then
	    die "Can't determine source repository without help. Try using an argument."
	fi
else
	cd $1
	export CODEMGR_WS=`pwd`
fi

# Set up your environment ala bldenv or ws.  Eventually this hack
# should go away.
export SRC=$CODEMGR_WS/usr/src
export MACH=`uname -p`
export ROOT=$CODEMGR_WS/proto/root_$MACH
export ENVCPPFLAGS1=-I$ROOT/usr/include
export ENVLDLIBS1="-L$ROOT/lib -L$ROOT/usr/lib"
export BUILD_TOOLS=/opt
export MAKEFLAGS=-e
#NOTE use gcc-only build
export CW_NO_SHADOW=1
export __GNUC=

#######
# THESE will vary depending on which illumos distro you run.
# You can also specify them in your environment, overriding what we calculate.
# OmniOS examples
export GCC_ROOT=${GCC_ROOT:-/opt/gcc-4.4.4}
export SPRO_ROOT=${SPRO_ROOT:-/opt/sunstudio12.1}

# OpenIndiana examples.
# Stock GCC_ROOT works on OI...
# export SPRO_ROOT=/opt/SUNWspro
########

# Make sure dmake is in your path, and TOOLS are first.
export PATH=$BUILD_TOOLS/onbld/bin:$BUILD_TOOLS/onbld/bin/$MACH:$SPRO_ROOT/bin:$PATH

export NO_GENUNIX_UNIQUIFY=
export CW_NO_SHADOW=1

(cd $SRC; dmake rootdirs) || exit 1
(cd $SRC/head; dmake) || exit 1
(cd $SRC/uts; dmake install_h) || exit 1

(cd $SRC; dmake libheaders) || exit 1
(cd $SRC/lib/libzfs; dmake install_h) || exit 1
(cd $SRC/uts/common/sys; dmake install_h) || exit 1

directories=(
	$SRC/uts/intel/kmdb
	$SRC/uts/intel/zfs
	$SRC/uts/intel/dev
	$SRC/man/man1m
	$SRC/man/man5
	$SRC/grub
	$SRC/lib/libc
	$SRC/lib/libavl
	$SRC/lib/libnvpair
	$SRC/lib/libsec
	$SRC/lib/libcmdutils
	$SRC/lib/libdevinfo
	$SRC/lib/libuutil
	$SRC/lib/libbrand
	$SRC/lib/libzonecfg
	$SRC/lib/libinetutil
	$SRC/lib/libdladm
	$SRC/lib/libdlpi
	$SRC/lib/libdiskmgt
	$SRC/lib/libumem
	$SRC/lib/libdisasm
	$SRC/lib/libidmap
	$SRC/lib/libdevid
	$SRC/lib/libzfs_core
	$SRC/lib/libzpool
	$SRC/lib/libzfs
	$SRC/lib/pyzfs
	$SRC/lib/libzfs_jni
	$SRC/lib/libsaveargs
	$SRC/cmd/isaexec
	$SRC/cmd/platexec
	$SRC/cmd/devfsadm
	$SRC/cmd/syseventd
	$SRC/cmd/fstyp
	$SRC/cmd/availdevs
	$SRC/cmd/fs.d/zfs
	$SRC/cmd/zdb
	$SRC/cmd/zhack
	$SRC/cmd/zfs
	$SRC/cmd/pyzfs
	$SRC/cmd/zinject
	$SRC/cmd/zpool
	$SRC/cmd/zstreamdump
	$SRC/cmd/ztest
	$SRC/cmd/terminfo
	$SRC/cmd/mdb
)

for i in "${directories[@]}"; do
	(cd $i; dmake install) || exit 1
done
