#!/usr/bin/env bash set -e function detect_platform_type () { local -r canon_name="canon-name/src/canon-name" if ! gmake --question --file="mk/canon-name.mk" >/dev/null 2>&1; then gmake --file="mk/canon-name.mk" >&2 fi "$canon_name" } function detect_number_of_cpus () { if sysctl -n "hw.ncpu" 2>/dev/null; then # This works for most BSDs. : elif grep -qF processor /proc/cpuinfo 2>/dev/null; then # Linux sucks... grep -cF processor /proc/cpuinfo else echo "WARNING: I don't know how to detect the number of processors on this platform." >&2 echo "WARNING: GHC will be built using only 1 processor. Expect some slowdown." >&2 echo 1 fi } function detect_gnu_tar () { if which gnutar >/dev/null 2>&1; then echo "gnutar" elif which gtar >/dev/null 2>&1; then echo "gtar" else echo "We need GNU tar to be installed." >&2 exit 1 fi } function detect_gnu_sed () { if which gsed >/dev/null 2>&1; then echo "gsed" elif sed --version | grep -qF GNU; then echo "sed" else echo "We need GNU sed to be installed." >&2 exit 1 fi } function say_hello () { local -r self=$(basename "$0") local -r platform=$(detect_platform_type) local -r n_cpus=$(detect_number_of_cpus) echo -n "This is $self, running on $platform with $n_cpus " if (( $n_cpus == 1 )); then echo "processor." else echo "processors." fi } function srcpath () { local -r archive="work/archive" local srcpath="" if [[ -e "$archive" ]]; then srcpath=$(cat "$archive") fi if [[ -z "$srcpath" || ! -e "$srcpath" ]]; then mkdir -p work read -e -p "Enter the file path to ghc-x.y.z-src.tar.bz2: " srcpath if [[ -e "$srcpath" ]]; then mkdir -p work echo "$srcpath" > "$archive" else echo "$srcpath not found." >&2 exit 1 fi fi echo "$srcpath" } function build_hc_pkg () { local -r srcpath="$(srcpath)" gmake \ -j $(($(detect_number_of_cpus) + 1)) \ -f mk/main.mk \ SRCPATH="$srcpath" \ PLATFORM="$(detect_platform_type)" \ GNUTAR="$(detect_gnu_tar)" \ GNUSED="$(detect_gnu_sed)" \ SHELL="$SHELL" echo "If you are done, run \"$0 clean\" to cleanup the working directory." } function main () { case "$1" in "") say_hello build_hc_pkg exit ;; "clean") echo "Cleaning..." rm -rf work exit ;; *) echo "Usage: $0 [clean]" >&2 exit 1 ;; esac } main $@