#!/bin/sh
# Copyright © 2012-2013  Alicia Coder
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, version 3 of the License.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
#
# You can obtain a copy of the GNU Affero General Public License from http://www.gnu.org/licenses/agpl-3.0.txt

# If you want to skip all the setup and sanity checks and get right to where we build things, search for "Building stuff starts here"

buildhome="`pwd`"
export PATH="${buildhome}/tools-prefix/bin:${PATH}"
export LD_LIBRARY_PATH="`echo "$LD_LIBRARY_PATH:${buildhome}/tools-prefix/lib" | sed -e 's/::*/:/g;s/^::*//;s/::*$//;'`" # The sed is to make glibc happy, not having any empty entries (=current directory) in the library path
buildroot="${buildhome}/root"
hosttriplet="i586-aos-linux-gnu" # Note: for x86 use i586 because glibc's buildsystem is broken and can't handle i686

# uname -so:
# Linux GNU/Linux      = linux-gnu
# MINGW32_NT-5.1 Msys  = mingw32
# Darwin (-o = error)  = darwin8.1.0 (uname -r = 8.1.0)
# FreeBSD FreeBSD      = freebsd
# CYGWIN_NT-5.1 Cygwin = cygwin
# SunOS Solaris        = solaris
buildkernel="`uname -s`"
buildos="`uname -o 2> /dev/null`"
if [ "$buildos" = "" ]; then # takes care of darwin (OSX)
  buildos="${buildkernel}`uname -r`"
elif [ "$buildos" != "$buildkernel" -a "$buildos" != "Solaris" ]; then # takes care of freebsd (kinda backwards, FreeBSD should not be kernel-OS, nor should Solaris)
  buildos="${buildkernel}-${buildos}"
fi
expr="s/[_\/].*//;"
buildos="`echo "$buildos" | tr '[:upper:]' '[:lower:]' | sed -e "$expr"`"
if [ "$buildos" = "mingw32" ]; then echo "mingw is not supported, if you want to attempt building from windows try cygwin instead"; exit 1; fi # because mingw requires way too many hacks
cpu="`uname -m | sed -e 's/i86pc/i386/;'`"
buildtriplet="${cpu}-buildtmp-${buildos}"

makejobs=1 # can be set with -m,--makejobs N
interactive=true # can be toggled with -i,--noninteractive
tmux=false # can be toggled with -t,--tmux
clean=false # can be toggled with -c,--clean
sparse=false # can be toggled with -s,--sparse
linuxconfig='' # can be set with -l,--linuxconfig
progressbar=false # can be toggled with --progressbar
bgdownloads=false # can be toggled with -g,--background
configarch='' # can be set with -a, --arch
skipwifi=false # can be toggled with --nowifi

setval=""
args=""
while [ "$#" -gt "0" ]; do
  if [ "$1" != "-t" -a "$1" != "--tmux" ]; then args="$args '${1}'"; fi
  if [ "$setval" = "makejobs" ]; then makejobs="$1"; setval=""
  elif [ "$setval" = "buildtriplet" ]; then buildtriplet="$1"; setval=""
  elif [ "$setval" = "linuxconfig" ]; then linuxconfig="$1"; setval=""
  elif [ "$setval" = "hostcpu" ]; then cpu="$1"; if [ "$cpu" = "i686" ]; then cpu="i586"; fi; hosttriplet="${cpu}-aos-linux-gnu"; setval=""
  elif [ "$setval" = "configarch" ]; then configarch="--with-arch=$1"; setval=""
  elif [ "$1" = "-h" -o "$1" = "--help" ]; then
    echo "Usage: ${0} [OPTIONS]"
    echo "-h,--help            = show this help text"
    echo "-m,--makejobs N      = set the number of makejobs to run simultaneously"
    echo "                       e.g. make -jN"
    echo "-i,--noninteractive  = make the build as automated as possible, mostly"
    echo "                       just disables linux menuconfig"
    echo "-b,--buildtriplet X  = override the buildtriplet and set it to X"
    echo "-t,--tmux            = launch the build in tmux with a bottom pane"
    echo "                       following the status log"
    echo "   --progressbar     = add a progressbar in tmux (experimental)"
    echo "-c,--clean           = clean up build directory, delete everything made"
    echo "                       during build except for downloaded archive files"
    echo "-s,--sparse          = use diskspace sparsely, remove source after"
    echo "                       building etc."
    echo "-l,--linuxconfig X   = use the linux configuration at path X instead"
    echo "                       of running defconfig, might require answering"
    echo "                       questions about options that changed"
    echo "-g,--background      = run downloads in the background, simultaneous to"
    echo "                       builds (EXPERIMENTAL)"
    echo "-p,--hostcpu CPU     = build AOS for CPU, default: i586"
    echo "-a,--arch CPU-arch   = build AOS for CPU-arch (more specific),"
    echo "                       passed to gcc's configure as --with-arch=..."
    echo "   --nowifi          = don't build any tools necessary to connect"
    echo "                       to wifi (EXPERIMENTAL)"
    exit 0
  elif [ "$1" = "-m" -o "$1" = "--makejobs" ]; then setval="makejobs"
  elif [ "$1" = "-i" -o "$1" = "--noninteractive" ]; then interactive=false
  elif [ "$1" = "-b" -o "$1" = "--buildtriplet" ]; then setval="buildtriplet"
  elif [ "$1" = "-t" -o "$1" = "--tmux" ]; then tmux=true
  elif [ "$1" = "-c" -o "$1" = "--clean" ]; then clean=true
  elif [ "$1" = "-s" -o "$1" = "--sparse" ]; then sparse=true
  elif [ "$1" = "-l" -o "$1" = "--linuxconfig" ]; then setval="linuxconfig"
  elif [ "$1" = "-g" -o "$1" = "--background" ]; then bgdownloads=true
  elif [ "$1" = "-p" -o "$1" = "--hostcpu" ]; then setval="hostcpu"
  elif [ "$1" = "-a" -o "$1" = "--arch" ]; then setval="configarch"
  elif [ "$1" = "--progressbar" ]; then progressbar=true
  elif [ "$1" = "--nowifi" ]; then skipwifi=true
  else
    echo "Unknown argument \"${1}\", try ${0} --help"
    exit 1
  fi
  shift
done

libsuffix=''
if echo "$hosttriplet" | grep -q '^x86_64-' || echo "$hosttriplet" | grep -q '^amd64-'; then libsuffix='64'; fi
if echo "$hosttriplet" | grep -q '^arm-'; then hosttriplet="${hosttriplet}eabi"; fi # gcc no longer supports arm without eabi (I'm not very familiar with it, I hope it's not something desirable)

# Checks to make sure parameter values are valid, e.g. -m's value has to be numeric, -l's value has to be an accessible file
if [ "$linuxconfig" != "" ] && ! grep -q CONFIG_LOCALVERSION "$linuxconfig" && ! gzip -d < "$linuxconfig" | grep -q CONFIG_LOCALVERSION; then echo "Error: ${linuxconfig} does not appear to be a Linux configuration file" >&2; exit 1; fi
if ! [ "0" -lt "$makejobs" ]; then echo "Error: number of makejobs (-m or --makejobs) has to be a positive integer" >&2; exit 1; fi
if "$bgdownloads" && ! echo | tail --pid=0; then echo "Note: disabling background downloads because tail does not support --pid=..."; bgdownloads=false; fi

# Just clean up builds but keep downloaded archives to avoid having to re-download them if building again
if "$clean"; then
  # check for any mounted partitions in the new root and tell the user to unmount them first
  rootdev="`stat -c '%D' root/ 2> /dev/null || stat -f '%d' root/ 2> /dev/null`" # Support GNU stat and BSD stat
  mounted=false
  skipmounts='empty'
  for x in root/*/ root/*/*/; do # Only bother going 2 levels in
    if [ ! -e "$x" ]; then continue; fi # no directories at that level
    for skip in $skipmounts; do
      if echo "$x" | grep -q "^$skip"; then
        continue 2 # Don't mention every file/directory within a mount
      fi
    done
    dev="`stat -c '%D' "$x" 2> /dev/null || stat -f '%d' "$x"`"
    if [ "$dev" != "$rootdev" ]; then
      skipmounts="${skipmounts} ${x}"
      mounted=true
      echo "${x} is on a different device than the root directory"
    fi
  done
  if "$mounted"; then echo "Please unmount all mountpoints in the new root before cleaning"; exit 1; fi
  find root/ -mindepth 1 -delete 2> /dev/null # Special for root, in case root is a symlink (rm -rf root/* would miss hidden files)
  rm -rf tools-prefix tools-src src/*/ status.log
  exit 0
fi

# Re-launching self with tmux to show status.log
if "$tmux"; then
  true > status.log # otherwise tail will immediately exit
  tmux new -d -s auto_build_aos
  tmux send-keys -t auto_build_aos "${0}${args}
"
  (
  sleep 1 # Delay it to make 'attach' resize the terminal first, so these 8 lines don't get resized along with it
  tmux split-window -v -l 8 -t auto_build_aos "tail -f status.log"
  if "$progressbar"; then
    steps="`grep '^ *report "[^"]' "$0" | wc -l | tr -d ' '`" # some wc add whitespace
    steps="`expr "$steps" - 1`" # Skipping one because there are two mutually exclusive reports for copying sources, one for all sources and one for just the linux source tree
    if ! "$interactive"; then steps="`expr "$steps" - 1`"; fi # Skipping one step for kernel configuration if not interactive
    if "$skipwifi"; then steps="`expr "$steps" - 36`"; fi # 36 of the steps are for wifi stuff
    tmux split-window -v -l 1 -t auto_build_aos "steps=${steps}"'; step=0; tail -f status.log | while read x; do if echo "$x" | grep -q -v ": done"; then continue; fi; expr="s/.* //;"; width="`stty size <&2 | sed -e "$expr"`"; step="`expr "$step" + 1`"; x=""; percent="`expr "$step" "*" 100 / "$steps"`"; progress="`expr "$step" "*" "$width" / "$steps"`"; while [ "$progress" -gt "0" ]; do x="${x} "; progress="`expr "$progress" - 1`"; done; echo; echo "${percent}%"; printf "[42m${x}[00m"; done; sh'
    # Since the above is an ugly mess for being shoved into one line, here's a formatted and commented variant:
    # steps=${steps} # Taking ${steps} from the main script
    # step=0
    # tail -f status.log | while read x; do
    #   if echo "$x" | grep -q -v ": done"; then
    #     continue # Ignore lines that aren't about progress (whether it's weird output or something failing)
    #   fi
    #   expr="s/.* //;" # Some shells have trouble handling nested code with strings and `<commands>`
    #   width="`stty size <&2 | sed -e "$expr"`"
    #   step="`expr "$step" + 1`"
    #   x=""
    #   percent="`expr "$step" "*" 100 / "$steps"`"
    #   progress="`expr "$step" "*" "$width" / "$steps"`"
    #   while [ "$progress" -gt "0" ]; do
    #     x="${x} "
    #     progress="`expr "$progress" - 1`"
    #   done
    #   echo # because we don't print a newline after the progressbar, do it now instead
    #   echo "${percent}%"
    #   printf "[42m${x}[00m" # <start green background><bar made of spaces><end green background>
    # done
    # sh # added for debugging, doesn't really do anything now
  fi
  tmux select-pane -t 0
  ) &
  tmux attach -t auto_build_aos
  exit 0
fi

echo "The buildscript has determined that the build-triplet for your system is ${buildtriplet}, if this is incorrect please edit build.sh and contribute a fix"
which() # Some systems' which are just plain broken, most of all OSX's which returns 0 unconditionally
{
  prog="$1"
  for path in `echo "$PATH" | sed -e 's/:/ /g'`; do
    if [ -x "${path}/${prog}" ]; then
      echo "${path}/${prog}"
      return 0
    fi
  done
  return 1
}
sed=sed
if which gmake > /dev/null 2> /dev/null; then alias make=gmake; fi
if which gsed > /dev/null 2> /dev/null; then alias sed=gsed; sed=gsed; fi
if which gmsgfmt > /dev/null 2> /dev/null; then alias msgfmt=gmsgfmt; fi
if which ginstall > /dev/null 2> /dev/null; then mkdir -p "${buildhome}/tools-prefix/bin"; ln -s "`which ginstall`" "${buildhome}/tools-prefix/bin/install" 2> /dev/null; fi # If there is a separate GNU install available that's probably what we want to use
if ! which cc > /dev/null 2> /dev/null && which gcc > /dev/null 2> /dev/null; then mkdir -p "${buildhome}/tools-prefix/bin"; ln -s "`which gcc`" "${buildhome}/tools-prefix/bin/cc" 2> /dev/null; fi # libgpg-error requires a compiler named cc
statusfile="${buildhome}/status.log"

# For Linux config:
expr='s/-.*//; s/^i[3-6]86$/x86/; s/^arm.*/arm/; s/^mips.*/mips/; s/^amd64$/x86_64/;'
arch="`echo "$hosttriplet" | sed -e "$expr"`" # 1. strip out non-cpu info, 2. fix x86, 3. fix arm, 4. fix mips, 5. fix amd64

reporttask=""
report()
{
  res="$?"
  if [ "$reporttask" != "" ]; then
    if [ "$res" = "0" ]; then
      echo "done" >> "$statusfile"
    else
      echo "failed" >> "$statusfile"
      if [ "$2" != "noncritical" ]; then # If it's not critical, don't bother with a rescue shell
        echo "Failed to ${reporttask}"
        # Ask the user if they want to launch a rescue shell
        echo "If you want you can launch a rescue shell and try to fix and finish the task yourself, when the shell exits the build will continue with the next step."
        printf "Do you wish to launch a rescue shell? (y/n) "
        read x
        if echo "$x" | grep -q -i '^y'; then
          sh # launch rescue shell
        else
          exit 1 # or exit
        fi
      fi
    fi
  fi
  if [ "$1" != "" ]; then
    printf "%s" "${1}: " >> "$statusfile"
  fi
  reporttask="$1"
  return 0 # This can later be used to skip steps already done
}

wgetwrapper()
{
  file="`basename "$1"`"
  if wget -c "$1"; then
    return 0 # Download successful
  elif [ -e "$file" ]; then
    return 0 # Not successful but the file exists, so maybe it was already downloaded, tar will tell
  else
    return 1 # No file = error
  fi
}

mkdir -p "$buildroot"
pressenter=true
# Check that we have everything we need to build AOS, repeat checks until they pass
while "$pressenter"; do
  pressenter=false
  if touch "${buildroot}/writetest$$"; then rm -f "${buildroot}/writetest$$"; else echo "The root directory/filesystem (${buildroot}) is unwritable, fix it"; pressenter=true; fi
  if [ "`which which`" = "" ]; then echo "Install which"; pressenter=true; fi
  if [ "`which wget`" = "" ]; then echo "Install wget"; pressenter=true; fi
  # check if make is GNU make and tell the user to install it otherwise
  if ! make --version 2> /dev/null | head -n 1 | grep -q "GNU Make "; then
    echo "Install GNU make"; pressenter=true
  fi
  if [ "`which gawk`" = "" ]; then echo "Install gawk"; pressenter=true; fi # Needed by glibc and probably others (glibc specifically needs GNU awk)
  if ! sed --version | head -n 1 | grep -q 'GNU sed[ )]'; then echo "Install GNU sed"; pressenter=true; fi
  if [ "`which tic`" = "" ]; then echo "Install tic (ncurses)"; pressenter=true; fi # tic from ncurses is needed while installing ncurses, and when crosscompiling we can't use the just-built one
  if [ "`which perl`" = "" ]; then echo "Install perl"; pressenter=true; fi # perl is needed for linux's buildsystem, and probably a few others
  if [ "`which bison`" = "" ]; then echo "Install bison 2.3b or later"; pressenter=true; fi # needed by bash, and probably others
  if [ "`which flex`" = "" ] && ! "$skipwifi"; then echo "Install flex version 2.5.19 or later"; pressenter=true; fi # needed by libnl, and probably others
  if [ "`which msgfmt`" = "" ]; then echo "Install GNU msgfmt (gettext)"; pressenter=true; fi # needed by net-tools at install stage
  if [ "`which xz`" = "" ]; then echo "Install xz"; pressenter=true; fi
  if [ "`which gzip`" = "" ]; then echo "Install gzip"; pressenter=true; fi
  if [ "`which bzip2`" = "" ]; then echo "Install bzip2"; pressenter=true; fi
  if [ "`which m4`" = "" ]; then echo "Install m4"; pressenter=true; fi # needed to build gmp
  if [ "`which patch`" = "" ]; then echo "Install patch (optional, used to patch bash)"; pressenter=true; fi # needed to patch bash
  if (flex --version | grep ' 1\.' || flex --version | grep ' 2\.[01234]\.' || flex --version | grep ' 2\.5\.[0-9]$' || flex --version | grep ' 2\.5\.1[0-8]$') 2> /dev/null && ! "$skipwifi"; then
    echo "Install flex version 2.5.19 or later"; pressenter=true # needed by libnl which passes --header-file to flex
  fi
  if ! msgfmt --statistics /dev/null > /dev/null 2> /dev/null; then echo "Install GNU msgfmt (gettext)"; pressenter=true; fi # kbd requires msgfmt that accepts --statistics, presumably it's GNU's implementation we need for that
  if (bison --version | grep -q ') [0-1]\.' || bison --version | grep -q ') 2\.[0-2][^0-9]' || bison --version | grep -q ') 2\.3[^0-9b-z]' || bison --version | grep -q ') 2\.3$') 2> /dev/null && ! "$skipwifi"; then echo "Install bison 2.3b or later"; pressenter=true; fi # needed by libnl, for '%define api.pure' primarily
  if [ "`which pkg-config`" = "" ]; then echo "Install pkg-config"; pressenter=true; fi # needed for iw
  if ! "`gcc -print-prog-name=ld 2> /dev/null`" -v 2> /dev/null | grep -q GNU; then echo "Install GNU ld (binutils) and make sure that's the linker gcc uses (gcc -print-prog-name=ld)"; pressenter=true; fi # Other linkers may cause problems, e.g. Solaris linker doesn't work well with gmp
  if ! which bc > /dev/null || echo 'hz=1000' | bc 2>&1 | grep -q 'syntax error'; then echo "Install a version of bc that doesn't get syntax errors for 'hz=1000'"; pressenter=true; fi # Needed by Linux

  if "$pressenter"; then printf "Then press enter to continue..."; read x; fi
  if which gmake > /dev/null 2> /dev/null; then alias make=gmake; fi
done

if echo "$buildhome" | grep -q '[^-/a-zA-Z0-9_]'; then printf "Building AOS in unusual paths is a bad idea (e.g. non-alphanumeric, spaces or international characters in directory names). Press enter to ignore this and attempt to build in '${buildhome}' anyway"; read x; fi
caseless=false; touch CaseTest; if [ -e caseTEST ]; then rm -f CaseTest; caseless=true; printf "Building AOS in a case-insensitive filesystem is problematic, but there are some workarounds, so press enter to continue anyway"; read x; fi; rm -f CaseTest

# Redo these tests in case the user installed GNU variants after being asked to
if which gmake > /dev/null 2> /dev/null; then alias make=gmake; fi
if which gsed > /dev/null 2> /dev/null; then alias sed=gsed; sed=gsed; fi
if which gmsgfmt > /dev/null 2> /dev/null; then alias msgfmt=gmsgfmt; fi
if which ginstall > /dev/null 2> /dev/null; then mkdir -p "${buildhome}/tools-prefix/bin"; ln -s "`which ginstall`" "${buildhome}/tools-prefix/bin/install" 2> /dev/null; fi # If there is a separate GNU install available that's probably what we want to use
nomath=false
if ! echo '#include <math.h>' | gcc -x c -c - -o /dev/null; then nomath=true; fi

if "$bgdownloads"; then
  bgdl()
  {
    job="$1"
    url="$2"
    sh -c 'echo "'"$job"'-PID:$$" >&2; wget -c '"$url" 2>&1 # TODO: can we somehow pipe stderr to wget or otherwise fool it into thinking it has a full terminal so that it will print a progressbar that we can tail onto?
  }
  wgetwrapper() # Substitute for regular wgetwrapper
  {
    file="`basename "$1"`"
    job="`echo "$file" | sed -e "s/\..*//;"`"
    pid="`sed -n -e "/^${job}-PID:[0-9]/{s/.*://;p;}" "${buildhome}/dl.log" | tail -n 1`"
    while [ "$pid" = "" ]; do
      echo "Waiting for ${job} download to start..." # This shouldn't really happen at all
      sleep 5
      pid="`sed -n -e "/^${job}-PID:[0-9]/{s/.*://;p;}" "${buildhome}/dl.log" | tail -n 1`"
    done
#  echo "PID is $pid (ours is $$)"
#  sleep 1
    tail --pid="$pid" -n 1 -f "${buildhome}/dl.log"
    # Check that the file exists before we exit
    if [ -e "$file" ]; then
      return 0 # The file exists, so it was probably successful, if not, tar will tell
    else
      return 1 # The file doesn't exist, something obviously went wrong
    fi
  }

#  echo "Files to download:"
  expr1='s/wgetwrapper[ ]/\n&/gp'
  expr2='/wgetwrapper/{s/wgetwrapper[ ]"*//;s/[" )].*//;p;}'
  # Extract URLs to download from self
  files="`sed -n -e "$expr1" "$0" | sed -n -e "$expr2"`"
#  echo "$files"
#exit
  true > "${buildhome}/dl.log"
  mkdir -p "${buildhome}/src"
  (
  for url in $files; do
    cd "${buildhome}/src" || exit # if the source directory is gone someone clearly wanted to cancel things
    bgdl "`basename "$url" | sed -e "s/\..*//;"`" "$url"
#    echo "bgdl '`basename "$url" | sed -e "s/\..*//;"`' '${url}'"
#    sleep 1
  done
  echo "# All downloads completed"
  ) > "${buildhome}/dl.log" &
fi

# Export any variables that we may want to keep in rescue shells
export hosttriplet
export buildtriplet
export buildhome
export buildroot
export arch
export libsuffix
# Mostly for diagnostics
export caseless
export buildos
export buildkernel

mkdir -p src
mkdir -p tools-src
mkdir -p tools-prefix

# Hacks, mostly for portability:

linux_portability_hacks()
{
# Necessary to build from FreeBSD (and probably a few other platforms)
sed -i -e "/^#include[ \t]*<byteswap\.h>/{s/.*/  &\n#endif/;i/** Wrappers for OS dependent byte swapping functions */
i#if defined(__FreeBSD__)
i#include <sys/endian.h>
i#define bswap_16(x) bswap16(x)
i#define bswap_32(x) bswap32(x)
i#define bswap_64(x) bswap64(x)
i#elif defined(DARWIN)
i#include <libkern/OSByteOrder.h>
i#define bswap_16(x) OSSwapInt16(x)
i#define bswap_32(x) OSSwapInt32(x)
i#define bswap_64(x) OSSwapInt64(x)
i#elif defined(sun)
i#include <sys/byteorder.h>
i#define bswap_16(x) BSWAP_16(x)
i#define bswap_32(x) BSWAP_32(x)
i#define bswap_64(x) BSWAP_64(x)
i#else
}; s/^[ \t]*#include[ \t]*<endian\.h>/\/\/ &/;" arch/x86/tools/relocs.h
expr='s/.*://;s/  */ /g;s|/.*||;s/$/\\/'
sed -i -e "/#include <elf\.h>/a`grep '#define R_' arch/*/include/asm/elf.h | sed -e "$expr"`
#define R_386_16 20\r\
#define R_386_PC16 21\r\
#define R_386_8 22\r\
#define R_386_PC8 23" arch/x86/tools/relocs.h # Not all systems define these in <elf.h>
sed -i -e 's/<linux.*/<stdint.h>\ntypedef __uint8_t __u8;\ntypedef __uint16_t __u16;\ntypedef __uint32_t __u32;\ntypedef __uint64_t __u64;/' tools/include/tools/le_byteshift.h
sed -i -e 's/<linux.*/"le_byteshift.h"/' tools/include/tools/be_byteshift.h
sed -i -e 's/(|/(X*|/g;s/|)/|X*)/g' arch/x86/tools/relocs.c # Some regex implementations do not accept empty subexpressions
if [ "$sed" = "gsed" ]; then # linux depends on sed being GNU sed
  sed -i -e 's/ sed/ gsed/' arch/x86/boot/Makefile
  sed -i -e "s/\tsed /\t${sed} /" arch/*/kernel/cpu/mkcapflags.sh # Linux depends on GNU sed
fi
if bc --version 2>&1 | grep -q BSD; then # Doesn't work quite right with non-GNU bc (note: GNU bc's --version output doesn't explicitly state GNU, but if we want to make this if-statment less BSD-specific we could look for absence of "Free Software Foundation")
  # With BSD's bc we get weird junk at the end, so cut off after '.endif.*KERNEL_TIMECONST' to skip it
  sed -i -e "s@\(cmd_bc.*\)>@\1| ${sed} -e '/^.endif.*KERNEL_TIMECONST/q' >@" kernel/Makefile
fi
}

linux_makefree() # like linux-libre, but without censorship and intentional, unproductive crippling
{
# Find list of nonfree firmwares and remove those (but don't bother with complete linux-libre as it breaks the functionality to load alternative, free firmware in their place and is overall too much of a control freak)
report "disable proprietary firmwares packaged with linux"
cat > liberate.sh << "ENDHEAD"
#!/bin/sh
# Liberation-script to remove proprietary firmwares, generated from Linux-libre's logfile (http://linux-libre.fsfla.org/pub/linux-libre/releases/3.11-gnu/linux-libre-3.11-gnu.log)
kconfigs="`find . -name "Kconfig"`"
noteblob()
{
  for kconfig in `grep -l '^config  *'"$1"'$' $kconfigs`; do # Find Kconfigs that contain the config symbol
    sed -i -e '/^config  *'"$1"'$/{n;s/(Blobs!) //g; s/"/"(Blobs!) /;}' "$kconfig" # First remove any previous markings
  done
  echo "CONFIG_${1}=n" >> .config
}
ENDHEAD
wget -q -O - "http://linux-libre.fsfla.org/pub/linux-libre/releases/3.11-gnu/linux-libre-3.11-gnu.log" | sed -n -e 's/^\(.*\): removed$/echo ':00000001FF' > \1/p; s/^\([^ abcdefghijklmnopqrstuvwxyz]*\) - ...*/noteblob "\1"/p;' >> liberate.sh
sed -i -e "/echo :00000001FF > .*\.H16\$/{s/:00000001FF/:000000000000FF/;}" liberate.sh # This should fix H16 ones
chmod +x liberate.sh
}

binutils_hacks()
{
sed -i -e '/^%.*\(colophon\|cygnus\)/{s/@/@@/;}' bfd/doc/bfd.texinfo # Fix bad texinfo
if "$nomath"; then
  sed -i -e 's|^#include <math|// &|' libiberty/floatformat.c
  sed -i -e 's|^#include "math|// &|' gprof/hist.c
fi
echo 'WARN_CFLAGS=' >> gprof/Makefile.in # Get rid of -Werror that causes errors on some platforms
}

gcc_hacks()
{
# Workaround for buggy texinfo source which earlier texinfo versions accepted as correct
sed -i -e 's/@itemx/@item/' gcc/doc/cpp.info
sed -i -e 's/@itemx/@item/' gcc/doc/gcc.info
sed -i -e 's/@itemx/@item/' gcc/doc/gccint.info
sed -i -e 's/@itemx/@item/' gcc/doc/invoke.texi
sed -i -e 's/@itemx/@item/' gcc/doc/cppopts.texi
sed -i -e 's/@itemx/@item/' gcc/doc/generic.texi
if "$nomath"; then
  echo 'double log(double);' > include/math.h
  echo 'double exp(double);' >> include/math.h
fi
}

# Building stuff starts here:

# Before everything else, configure linux and make headers_install to generate headers
cd "${buildhome}/src"
# Download kernel
report "download linux"
wgetwrapper http://www.kernel.org/pub/linux/kernel/v3.x/linux-3.11.tar.xz || wgetwrapper http://aos.ion.nu/sourcemirror/linux-3.11.tar.xz
report "unpack linux"
tar -xJf linux-3.11.tar.xz
report ""
# Configure and generate headers
cd linux-3.11
linux_portability_hacks
linux_makefree # generates liberate.sh
if [ "$linuxconfig" = "" ]; then
  if [ "$arch" = "x86" ]; then conf='i386_'; else conf=''; fi # Don't let linux's configure system assume we mean x86_64 when we say x86 just because the buildhost happens to be x86_64
  make "${conf}defconfig" ARCH="$arch" # Start with full defaults
  ./liberate.sh # liberate after generating a configuration
else
  ./liberate.sh # liberate before loading a configuration (not allowing it to disable any user-picked options)
  # in case the path is relative, go from $buildhome
  cd "$buildhome"
  if echo "$linuxconfig" | grep -q '\.gz$'; then
    gzip -dc "$linuxconfig" > "src/linux-3.11/.config"
  else
    cat "$linuxconfig" > "src/linux-3.11/.config"
  fi
  cd "src/linux-3.11"
fi
# Some sane/useful defaults
echo 'CONFIG_64BIT=n' >> .config # Prevent 32-bit targets from getting 64-bit kernels by default (if the buildhost is 64-bit) # Note: this does not turn 64-bit builds into 32-bit
echo 'CONFIG_LOCALVERSION="-aos"' >> .config # Set a default local version suffix
echo 'CONFIG_IKCONFIG=y' >> .config
echo 'CONFIG_IKCONFIG_PROC=y' >> .config
echo 'CONFIG_DEVTMPFS=y' >> .config
echo 'CONFIG_DEVTMPFS_MOUNT=y' >> .config
echo 'CONFIG_FIRMWARE_IN_KERNEL=n' >> .config
report
make silentoldconfig ARCH="$arch" 2> /dev/null # there will be warnings about overridden values, 64BIT, LOCALVERSION, etc. therefor 2> /dev/null
if "$interactive" && stty > /dev/null; then
  # check that terminal is 19 lines by 80 columns before launching menuconfig
  x=""
  while ! [ "`stty size | sed -e 's/ .*//;'`" -gt 18 -a "`stty size | sed -e 's/.* //;'`" -gt 79 ]; do
    printf "Resize your terminal to at least 19 rows, 80 columns and press enter to continue, or type 'skip' to skip configuring the kernel> "
    read x
    if [ "$x" = "skip" ]; then break; fi
  done
  if [ "$x" != "skip" ]; then
    report "configure linux"
    make menuconfig ARCH="$arch"
  fi
fi
report "generate headers for linux"
make headers_install ARCH="$arch" INSTALL_HDR_PATH="${buildhome}/tools-prefix/${hosttriplet}" # Note: this wipes out any other headers previously installed there, but there shouldn't be any at this point, right?
make headers_install ARCH="$arch" INSTALL_HDR_PATH="${buildroot}/usr" # Install headers into the new system too
report

# Build binutils for the toolchain
report "download binutils"
cd "${buildhome}/src"
wgetwrapper http://ftp.gnu.org/gnu/binutils/binutils-2.23.2.tar.bz2 || wgetwrapper http://aos.ion.nu/sourcemirror/binutils-2.23.2.tar.bz2
report "unpack binutils (toolchain)"
cd ../tools-src
tar -xjf ../src/binutils-2.23.2.tar.bz2
report
cd binutils-2.23.2
binutils_hacks
report "configure binutils (toolchain)"
./configure --prefix="${buildhome}/tools-prefix" --target="${hosttriplet}" --build="${buildtriplet}" --host="${buildtriplet}"
report "build binutils (toolchain)"
make -j"$makejobs"
report "install binutils (toolchain)"
make install
report
if "$sparse"; then rm -rf *; fi

# Build gmp for the toolchain
report "download gmp"
cd "${buildhome}/src"
wgetwrapper http://ftp.gnu.org/gnu/gmp/gmp-5.1.2.tar.xz || wgetwrapper http://aos.ion.nu/sourcemirror/gmp-5.1.2.tar.xz
cd ../tools-src
report "unpack gmp (toolchain)"
tar -xJf ../src/gmp-5.1.2.tar.xz
report
cd gmp-5.1.2
mkdir build
cd build
report "configure gmp (toolchain)"
../configure --prefix="${buildhome}/tools-prefix" --host="${buildtriplet}" --build="${buildtriplet}" --enable-static --disable-shared
report "build gmp (toolchain)"
make -j"$makejobs" # Note: doesn't mind -j#
# Note: make check doesn't work when cross-compiling
report "install gmp (toolchain)"
make install
report
if "$sparse"; then cd ..; rm -rf *; fi

# Build mpfr for the toolchain
cd "${buildhome}/src"
report "download mpfr"
wgetwrapper http://ftp.gnu.org/gnu/mpfr/mpfr-3.1.2.tar.xz || wgetwrapper http://aos.ion.nu/sourcemirror/mpfr-3.1.2.tar.xz
report "unpack mpfr (toolchain)"
cd ../tools-src
tar -xJf ../src/mpfr-3.1.2.tar.xz
report
mkdir -p mpfr-3.1.2/build
cd mpfr-3.1.2/build
report "configure mpfr (toolchain)"
../configure --prefix="${buildhome}/tools-prefix" --build="${buildtriplet}" --host="${buildtriplet}" --enable-static --disable-shared --with-gmp="${buildhome}/tools-prefix"
report "build mpfr (toolchain)"
make -j"$makejobs"
report "install mpfr (toolchain)"
make install
report
if "$sparse"; then cd ..; rm -rf *; fi

# Build gcc for the toolchain (initial boostrap)
cd "${buildhome}/src"
report "download gcc"
wgetwrapper http://ftp.gnu.org/gnu/gcc/gcc-4.8.1/gcc-4.8.1.tar.bz2 || wgetwrapper http://aos.ion.nu/sourcemirror/gcc-4.8.1.tar.bz2
report "unpack gcc (toolchain)"
cd ../tools-src
tar -xjf ../src/gcc-4.8.1.tar.bz2
report
cd gcc-4.8.1
gcc_hacks
# Fetch dependencies
report "download mpc (toolchain)"
(cd "${buildhome}/src"; wgetwrapper http://www.multiprecision.org/mpc/download/mpc-1.0.1.tar.gz || wgetwrapper http://aos.ion.nu/sourcemirror/mpc-1.0.1.tar.gz)
report "unpack mpc (toolchain)"
tar -xzf "${buildhome}/src/mpc-1.0.1.tar.gz"
report
mv mpc-1.0.1 mpc

mkdir -p build-bootstrap
cd build-bootstrap
report "configure gcc (toolchain bootstrap)"
../configure --prefix="${buildhome}/tools-prefix" --target="$hosttriplet" --build="$buildtriplet" --host="$buildtriplet" --with-mpfr="${buildhome}/tools-prefix" --enable-languages=c --without-headers --disable-decimal-float --disable-libgomp --disable-threads --disable-libssp --disable-shared --disable-libquadmath --disable-libmudflap --disable-libatomic --with-gmp="${buildhome}/tools-prefix" $configarch
report "build gcc (toolchain bootstrap)"
sed -i -e 's/ -static-libgcc//' Makefile # for some reason trying to link libgcc statically at this point seems to cause trouble in some cases (experienced when building on an x86_64 AOS system, nothing exotic)
make -j"$makejobs"
report "install gcc (toolchain bootstrap)"
make install
report
if "$sparse"; then rm -rf *; fi

# Build glibc
cd "${buildhome}/src"
report "download glibc"
wgetwrapper http://ftp.gnu.org/gnu/glibc/glibc-2.18.tar.xz || wgetwrapper http://aos.ion.nu/sourcemirror/glibc-2.18.tar.xz
report "unpack glibc (toolchainlib)"
cd "${buildhome}/tools-src"
tar -xJf ../src/glibc-2.18.tar.xz
report
cd glibc-2.18
if [ "$buildos" = "solaris" ]; then # I haven't figured out why, but CP774.so and a few others won't build on Solaris (still true with 2.18, and for more encodings)
  sed -i -e 's/\<[Cc][Pp]77[01234][^ ]*//g;' iconvdata/Makefile # Added for 2.18
  sed -i -e 's/\<ISO8859-9E[^ ]*//i;' iconvdata/Makefile # Added for 2.18
  # Note: I've noticed the default limit for open files on Solaris (or at least OpenIndiana) is 256 while on AOS it's 1024, I also saw some warnings about maximum number of files being open while building glibc, but that doesn't seem to be the reason for this failing
fi
if "$caseless"; then
  for x in `grep -rl '\.oS' .`; do sed -i -e 's/\.oS/&T/g' "$x"; done # Hack to differentiate filenames more than just upper/lowercase (for systems that can't tell the difference)
fi
# Minor fix for crosscompiling from platforms that don't define certain type names
sed -i -e '/#ifndef .*_defined/a#if !defined(__APPLE__) && !defined(__BSD__) && !defined(_BSDTYPES_DEFINED)' sunrpc/rpc/types.h
sed -i -e '/# define/i#endif' sunrpc/rpc/types.h
sed -i -e 's/g}/g;}/' Makerules # Needed for systems with non-GNU sed
sed -i -e 's/defined(__BSD__)/(& || defined(__FreeBSD__) || defined(__sun__))/' sunrpc/rpc/types.h
# Use GNU sed
if [ "$sed" != "sed" ]; then
  sed -i -e "1aalias sed=${sed}" sysdeps/unix/make-syscalls.sh
fi
# Not all systems have stat64, and when all it's used for is to check if a file exists (it seems) it doesn't matter if it's 64-bit or 32-bit
if ! (echo '#include <sys/stat.h>'; echo 'struct stat st; int main(){stat64("/",&st);}') | cc -x c - -o /dev/null; then
  sed -i -e 's/stat64/stat/g' sunrpc/rpc_main.c
fi
# Adjust for buildhosts lacking some specific types
if ! (echo '#include <sys/types.h>'; echo '__u_quad_t test;') | cc -x c -c - -o /dev/null; then
  sed -i -e 's/__quad_t/long long int/; s/__u_quad_t/long long unsigned/' sunrpc/rpc/types.h
  sed -i -e 's/typedef __u_/typedef unsigned /' sunrpc/rpc/types.h
  sed -i -e 's|^typedef __|// &|' sunrpc/rpc/types.h # Skip remaining types for simplicity
fi
mkdir -p build
cd build
report "configure glibc (toolchainlib)"
../configure --prefix="${buildhome}/tools-prefix/${hosttriplet}" --host="$hosttriplet" --build="$buildtriplet" libc_cv_forced_unwind=yes libc_cv_c_cleanup=yes libc_cv_ctors_header=yes ac_cv_header_cpuid_h=yes libc_cv_ssp=no ac_cv_prog_SED="$sed" # Hacks to get past checks that a bootstrap-compiler won't pass
report
# Hack to make glibc link with weird bootstrap-libgcc (lacking libgcc_eh.a and libgcc_s.a):
ln -s "`"${hosttriplet}-gcc" -print-libgcc-file-name`" "`"${hosttriplet}-gcc" -print-libgcc-file-name | sed -e "s/libgcc\(\.[^.]\)\$/libgcc_eh\1/"`"
ln -s "`"${hosttriplet}-gcc" -print-libgcc-file-name`" "`"${hosttriplet}-gcc" -print-libgcc-file-name | sed -e "s/libgcc\(\.[^.]\)\$/libgcc_s\1/"`"
report "build glibc (toolchainlib)"
if [ "$buildos" = "freebsd" ]; then echo 'BUILD_CC += -I/usr/local/include' >> config.make; fi # FreeBSD installs a lot of things in /usr/local
make -j"$makejobs"
report
# Undo the hack since it's not needed anymore
rm -f "`"${hosttriplet}-gcc" -print-libgcc-file-name | sed -e "s/libgcc\(\.[^.]\)\$/libgcc_eh\1/"`"
rm -f "`"${hosttriplet}-gcc" -print-libgcc-file-name | sed -e "s/libgcc\(\.[^.]\)\$/libgcc_s\1/"`"
report "install glibc (toolchainlib)"
make install
report
# Declare a bogus gets() to work around gnulib assuming it is always declared
sed -i -e "/\*gets *(/{n;i#else
iextern void gets(); // don't use this, we only declare it so that gnulib doesn't get errors
}" "${buildhome}/tools-prefix/${hosttriplet}/include/stdio.h"
if "$sparse"; then cd ..; rm -rf *; fi

# Re-compile gcc as non-bootstrap
cd "${buildhome}/tools-src/gcc-4.8.1"
mkdir -p build
cd build
report "configure gcc (toolchain)"
../configure --prefix="${buildhome}/tools-prefix" --target="$hosttriplet" --build="$buildtriplet" --host="$buildtriplet" --with-mpfr="${buildhome}/tools-prefix" --enable-languages="c,c++" --disable-multilib $configarch
report "build gcc (toolchain)"
sed -i -e 's/ -static-libgcc//' Makefile # for some reason trying to link libgcc statically at this point seems to cause trouble in some cases (experienced when building on an x86_64 AOS system, nothing exotic)
make -j"$makejobs"
report "install gcc (toolchain)"
make install
report
if "$sparse"; then cd ..; rm -rf *; fi

# Build file for toolchain (same version required natively when crosscompiling file)
cd "${buildhome}/src"
report "download file"
wgetwrapper ftp://ftp.astron.com/pub/file/file-5.14.tar.gz || ftp://ftp.fu-berlin.de/unix/tools/file/file-5.14.tar.gz || wgetwrapper http://aos.ion.nu/sourcemirror/file-5.14.tar.gz
report "unpack file (toolchain)"
cd ../tools-src
tar -xzf ../src/file-5.14.tar.gz
report "configure file (toolchain)"
cd file-5.14
mkdir build
cd build
../configure --prefix="${buildhome}/tools-prefix"
report "build file (toolchain)"
make -j"$makejobs" # Doesn't mind -j#
report "install file (toolchain)"
make install
report
if "$sparse"; then rm -rf *; fi

# Cross-toolchain complete, now build the system
export PKG_CONFIG_PATH="${buildhome}/tools-prefix/${hosttriplet}/lib/pkgconfig"

# Build linux
cd "${buildhome}/src/linux-3.11"

if [ "$buildos" = "freebsd" ]; then
  sed -i -e "s/^#include <sys\/sysmacros\.h>/#include <sys\/types.h>/" arch/x86/boot/tools/build.c # on FreeBSD sys/sysmacros.h is sys/types.h
fi
if [ "$buildos" = "solaris" ]; then # Solaris' elf.h does not have the constants that Linux's buildsystem depends on
  sed -i -e 's/<elf\.h>/"elf.h"/' scripts/mod/modpost.h
  cp "${buildhome}/tools-prefix/${hosttriplet}/include/elf.h" scripts/mod
  # Some mods are needed to build with this header without the rest of glibc:
  sed -i -e '/DECLS/d' scripts/mod/elf.h
  sed -i -e '/features\.h/d' scripts/mod/elf.h
  sed -i -e 's/<elf\.h>/"elf.h"/' arch/x86/boot/compressed/relocs.c
  cp scripts/mod/elf.h arch/x86/boot/compressed
  # Also endianness constants work differently:
  sed -i -e 's/#if BYTE_ORDER == LITTLE_ENDIAN/#ifndef _BIG_ENDIAN/; s/#if BYTE_ORDER == BIG_ENDIAN/#ifdef _BIG_ENDIAN/' arch/x86/boot/compressed/relocs.c
fi
if ! sh -e -c 'trap exit ERR'; then
  sed -i -e 's/ ERR//' scripts/link-vmlinux.sh
fi

report "build linux"
sed -i -e 's/\.macro cfi_ignore a=0, b=0, c=0, d=0$/&, e=0, f=0, g=0, h=0/' arch/x86/include/asm/dwarf2.h # Fix an error that manifests itself when compiling an x86_64 AOS from FreeBSD, resulting in lots of "too many positional arguments" errors in arch/x86/kernel/entry_64.S, (apicinterrupt ->) interrupt -> SAVE_ARGS_IRQ -> CFI_ESCAPE -> cfi_ignore
if [ "$buildos" = "cygwin" ]; then # Tweaks for linux's buildsystem to work on cygwin
  sed -i -e 's/pnmtologo :=.*/&.exe/' drivers/video/logo/Makefile
fi
if [ "$buildos" = "solaris" ]; then
  sed -i -e 's|^.*bswap|// &|' arch/x86/tools/relocs.c # Solaris seems to have byteorder messed up, both BYTEORDER == BIG_ENDIAN and BYTEORDER == LITTLE_ENDIAN resolve to true. TODO: fix this properly
fi
if "$caseless"; then
  # Case insensitivity! (I'm sure there are more cases of these if we stray from the default configuration)
  sed -i -e 's/_tcpmss\.o/_tcpmss_lower.o/;s/_TCPMSS\.o/_TCPMSS_upper.o/;' net/netfilter/Makefile
  tar -xJf ../linux-3.11.tar.xz linux-3.11/net/netfilter/xt_tcpmss.c linux-3.11/include/uapi/linux/netfilter/xt_tcpmss.h --transform='s/^[^\/]*\///;s/\.[ch]/_lower&/;'
  tar -xJf ../linux-3.11.tar.xz linux-3.11/net/netfilter/xt_TCPMSS.c linux-3.11/include/uapi/linux/netfilter/xt_TCPMSS.h --transform='s/^[^\/]*\///;s/\.[ch]/_upper&/;'
  sed -i -e 's/tcpmss\.h/tcpmss_lower.h/' net/netfilter/xt_tcpmss_lower.c
  sed -i -e 's/TCPMSS\.h/TCPMSS_upper.h/' net/netfilter/xt_TCPMSS_upper.c
fi
make -j"$makejobs" bzImage ARCH="$arch" CROSS_COMPILE="${hosttriplet}-"
report "build linux modules"
make -j"$makejobs" modules ARCH="$arch" CROSS_COMPILE="${hosttriplet}-"
report
linuxversion="`make kernelrelease | tail -n 1`"
mkdir -p "${buildroot}/boot"
report "install linux"
# It is not called bzImage on all platforms, so use a wildcard
cp "`ls arch/*/boot/*zImage | head -n 1`" "${buildroot}/boot/vmlinuz-${linuxversion}"
report "install linux modules"
make modules_install ARCH="$arch" CROSS_COMPILE="${hosttriplet}-" INSTALL_MOD_PATH="$buildroot"
report "install linux firmwares"
make firmware_install ARCH="$arch" CROSS_COMPILE="${hosttriplet}-" INSTALL_MOD_PATH="$buildroot"
report
if "$sparse"; then make clean; fi # Only clean, because the kernel tree is still needed for building external kernel modules

# Build glibc
cd "${buildhome}/src"
report "unpack glibc"
tar -xJf glibc-2.18.tar.xz
report
cd glibc-2.18
# Hack, shouldn't be necessary.. TODO: check if there is some configure check that fails due to crosscompiling that we can force a value for through cache. Still applies to glibc-2.18
echo "ifeq (yes,\$(have-ssp))" >> nscd/Makefile
echo "LDLIBS-nscd += -lssp" >> nscd/Makefile
echo "endif" >> nscd/Makefile
echo "ifeq (yes,\$(have-ssp))" >> resolv/Makefile
echo "LDLIBS-resolv.so += -lssp" >> resolv/Makefile
echo "endif" >> resolv/Makefile
if [ "$buildos" = "solaris" ]; then # I haven't figured out why, but CP774.so and a few others won't build on Solaris (still true with 2.18, and for more encodings)
  sed -i -e 's/\<[Cc][Pp]77[01234][^ ]*//g;' iconvdata/Makefile # Added for 2.18
  sed -i -e 's/\<ISO8859-9E[^ ]*//i;' iconvdata/Makefile # Added for 2.18
fi
if "$caseless"; then
  for x in `grep -rl '\.oS' .`; do sed -i -e 's/\.oS/&T/g' "$x"; done # Hack to differentiate filenames more than just upper/lowercase (for systems that can't tell the difference)
fi
# Minor fix for crosscompiling from platforms that don't define certain type names
sed -i -e '/#ifndef .*_defined/a#if !defined(__APPLE__) && !defined(__BSD__) && !defined(_BSDTYPES_DEFINED)' sunrpc/rpc/types.h
sed -i -e '/# define/i#endif' sunrpc/rpc/types.h
sed -i -e 's/g}/g;}/' Makerules # Needed for systems with non-GNU sed
sed -i -e 's/defined(__BSD__)/(& || defined(__FreeBSD__) || defined(__sun__))/' sunrpc/rpc/types.h
# Use GNU sed
if [ "$sed" != "sed" ]; then
  sed -i -e "1aalias sed=${sed}" sysdeps/unix/make-syscalls.sh
fi
# Not all systems have stat64, and when all it's used for is to check if a file exists (it seems) it doesn't matter if it's 64-bit or 32-bit
if ! (echo '#include <sys/stat.h>'; echo 'struct stat st; int main(){stat64("/",&st);}') | cc -x c - -o /dev/null; then
  sed -i -e 's/stat64/stat/g' sunrpc/rpc_main.c
fi
# Adjust for buildhosts lacking some specific types
if ! (echo '#include <sys/types.h>'; echo '__u_quad_t test;') | cc -x c -c - -o /dev/null; then
  sed -i -e 's/__quad_t/long long int/; s/__u_quad_t/long long unsigned/' sunrpc/rpc/types.h
  sed -i -e 's/typedef __u_/typedef unsigned /' sunrpc/rpc/types.h
  sed -i -e 's|^typedef __|// &|' sunrpc/rpc/types.h # Skip remaining types for simplicity
fi
mkdir build
cd build
report "configure glibc"
../configure --prefix="/usr" --exec-prefix="" --host="$hosttriplet" --build="$buildtriplet" --enable-add-ons ac_cv_prog_SED="$sed"
dirs="/usr/lib"
if [ "$libsuffix" != "" ]; then dirs="${dirs}:/usr/lib${libsuffix}"; fi
echo "user-defined-trusted-dirs = ${dirs}" >> config.make # make our dynamic linker search for libraries in /usr/lib too and not just /lib
report "build glibc"
if [ "$buildos" = "freebsd" ]; then echo 'BUILD_CC += -I/usr/local/include' >> config.make; fi # FreeBSD installs a lot of things in /usr/local
make -j"$makejobs" # Note: glibc doesn't mind -j#
report "install glibc"
make install install_root="$buildroot"
report
# Declare a bogus gets() to work around gnulib assuming it is always declared
sed -i -e "/\*gets *(/{n;i#else
iextern void gets(); // don't use this, we only declare it so that gnulib doesn't get errors
}" "${buildroot}/usr/include/stdio.h"
if "$sparse"; then cd ..; rm -rf *; fi

# Build gmp
cd "${buildhome}/src"
report "unpack gmp"
tar -xJf gmp-5.1.2.tar.xz
report
cd gmp-5.1.2
mkdir build
cd build
report "configure gmp"
../configure --prefix="/usr" --libdir="/lib${libsuffix}" --host="${hosttriplet}" --build="${buildtriplet}"
report "build gmp"
make -j"$makejobs" # Note: doesn't mind -j#
# Note: make check doesn't work when cross-compiling
report "install gmp"
make install DESTDIR="$buildroot"
report
mkdir ../build-toolchain
cd ../build-toolchain
report "configure gmp (toolchainlib)"
../configure --prefix="${buildhome}/tools-prefix/${hosttriplet}" --libdir="${buildhome}/tools-prefix/${hosttriplet}/lib${libsuffix}" --host="${hosttriplet}" --build="${buildtriplet}"
report "build gmp (toolchainlib)"
make -j"$makejobs" # Note: doesn't mind -j#
# Note: make check doesn't work when cross-compiling
report "install gmp (toolchainlib)"
make install
report
if "$sparse"; then cd ..; rm -rf *; fi

# Build mpfr
cd "${buildhome}/src"
report "unpack mpfr"
tar -xJf mpfr-3.1.2.tar.xz
report
mkdir -p mpfr-3.1.2/build
cd mpfr-3.1.2/build
report "configure mpfr"
../configure --prefix="/usr" --libdir="/lib${libsuffix}" --build="${buildtriplet}" --host="${hosttriplet}"
report "build mpfr"
make -j"$makejobs"
report "install mpfr"
make install DESTDIR="$buildroot"
report
mkdir ../build-toolchain
cd ../build-toolchain
report "configure mpfr (toolchainlib)"
../configure --prefix="${buildhome}/tools-prefix/${hosttriplet}" --libdir="${buildhome}/tools-prefix/${hosttriplet}/lib${libsuffix}" --build="${buildtriplet}" --host="${hosttriplet}"
report "build mpfr (toolchainlib)"
make -j"$makejobs"
report "install mpfr (toolchainlib)"
make install
report
if "$sparse"; then cd ..; rm -rf *; fi

# Build mpc
cd "${buildhome}/src"
report "unpack mpc"
tar -xzf mpc-1.0.1.tar.gz
report
cd mpc-1.0.1
mkdir build
cd build
report "configure mpc"
../configure --prefix="/usr" --libdir="/lib${libsuffix}" --host="${hosttriplet}" --build="${buildtriplet}" CC="${hosttriplet}-gcc"
report "build mpc"
make -j"$makejobs" # Note: doesn't mind -j#
report "install mpc"
make install DESTDIR="$buildroot"
report
mkdir ../build-toolchain
cd ../build-toolchain
report "configure mpc (toolchainlib)"
../configure --prefix="${buildhome}/tools-prefix/${hosttriplet}" --host="${hosttriplet}" --build="${buildtriplet}" CC="${hosttriplet}-gcc"
report "build mpc (toolchainlib)"
make -j"$makejobs" # Note: doesn't mind -j#
report "install mpc (toolchainlib)"
make install
report
if "$sparse"; then cd ..; rm -rf *; fi

# Build gcc
cd "${buildhome}/src"
report "unpack gcc"
tar -xjf gcc-4.8.1.tar.bz2
report
cd gcc-4.8.1
# Workaround for buggy texinfo source which earlier texinfo versions accepted as correct
sed -i -e 's/@itemx/@item/' gcc/doc/cpp.info
sed -i -e 's/@itemx/@item/' gcc/doc/gcc.info
sed -i -e 's/@itemx/@item/' gcc/doc/gccint.info
sed -i -e 's/@itemx/@item/' gcc/doc/invoke.texi
sed -i -e 's/@itemx/@item/' gcc/doc/cppopts.texi
sed -i -e 's/@itemx/@item/' gcc/doc/generic.texi
if "$nomath"; then
  echo 'double log(double);' > include/math.h
  echo 'double exp(double);' >> include/math.h
fi
# Note: we installed dependencies (gmp, mpfr, mpc) as toolchainlibs already so we don't have to put them in the gcc source directory
sed -i -e "s@INPUTLIST=.*@INPUTLIST=\"${buildroot}/usr/include\"@" fixincludes/fixinc.in # Hack to make fixincludes fix the right includes
sed -i -e '/HAVE_SYS_SDT/d' gcc/configure # We don't build systemtap (sys/sdt.h), but the buildsystem can get confused with cross-compiling if the buildhost has it
sed -i -e 's/^CFLAGS=.*GMPINC/& -DGENERATOR_FILE=1/' gcc/configure # Avoid confusion about whether the build host declares strstr etc.
# Make sure g++ uses the right include paths for C++ headers (by default it is relative to libdir, with the assumption that libdir is $prefix/lib)
sed -i -e 's|@gcc_gxx_include_dir@|@prefix@/include/c++/$(version)|' gcc/Makefile.in
# Remove some warning flags that caused errors on FreeBSD (and Solaris)
echo 'LOOSE_WARN=' >> gcc/Makefile.in
echo 'STRICT_WARN=' >> gcc/Makefile.in
echo 'WARN_CFLAGS=' >> libcpp/Makefile.in
echo 'WARN_CXXFLAGS=' >> libcpp/Makefile.in
if [ "$buildos" = "linux-gnu" ]; then
  disableplugin=''
else # TODO: check if this is necessary elsewhere (solaris, cygwin)
  disableplugin='--disable-plugin' # Can't handle plugins when crosscompiling it seems (at least not from FreeBSD)
fi
mkdir build
cd build
report "configure gcc"
../configure --prefix="/usr" --libdir="/lib${libsuffix}" --host="${hosttriplet}" --target="${hosttriplet}" --build="${buildtriplet}" --enable-languages="c,c++" --oldincludedir="${buildhome}/tools-prefix/${hosttriplet}/include" $configarch $disableplugin
report
# Hack to make cross-building gcc work (not sure if the issue comes from the fact that we're cross-compiling or from versions being different and some header no longer including it on its own, or from including c++ without a c++ crosscompiler, but I doubt that's it)
sed -i -e "1i#include <bits/posix1_lim.h>" ../gcc/config/host-linux.c
report "build gcc"
make -j"$makejobs" # doesn't mind -j#
report "install gcc"
sed -i -e "s@^libdir=@&${buildroot}@" */libsanitizer/asan/libasan.la # Hack to keep from linking to buildhost libraries
make install DESTDIR="$buildroot"
report
if "$sparse"; then cd ..; rm -rf *; fi

# Build binutils
cd "${buildhome}/src"
report "unpack binutils"
tar -xjf binutils-2.23.2.tar.bz2
report
cd binutils-2.23.2
sed -i -e '/^%.*\(colophon\|cygnus\)/{s/@/@@/;}' bfd/doc/bfd.texinfo # Fix bad texinfo
report "configure binutils"
./configure --prefix="/usr" --host="$hosttriplet" --build="$buildtriplet"
report "build binutils"
make -j"$makejobs" # Doesn't mind -j#
report "install binutils"
make install DESTDIR="$buildroot"
report
if "$sparse"; then rm -rf *; fi

# Build ncurses
cd "${buildhome}/src"
report "download ncurses"
wgetwrapper "http://ftp.gnu.org/gnu/ncurses/ncurses-5.9.tar.gz" || wgetwrapper http://aos.ion.nu/sourcemirror/ncurses-5.9.tar.gz
report "unpack ncurses"
tar -xzf ncurses-5.9.tar.gz
report
cd ncurses-5.9
mkdir build
cd build
report "configure ncurses"
../configure --prefix="/usr" --host="$hosttriplet" --build="$buildtriplet" --enable-widec --with-shared
report "build ncurses"
make # Does mind -j#, at least on some platforms
report "install ncurses"
make install DESTDIR="$buildroot"
report
ln -s libncursesw.a "${buildroot}/usr/lib/libncurses.a" # Make it easier for configure scripts to find ncurses (some only look for the non-wide version)
ln -s libncursesw.so "${buildroot}/usr/lib/libncurses.so"
mkdir ../build-toolchain
cd ../build-toolchain
report "configure ncurses (toolchainlib)"
../configure --prefix="${buildhome}/tools-prefix/${hosttriplet}" --host="$hosttriplet" --build="$buildtriplet" --enable-widec --with-terminfo-dirs="/usr/share/terminfo" --with-default-terminfo-dir="/usr/share/terminfo"
report "build ncurses (toolchainlib)"
make # Does mind -j#, at least on some platforms
report "install ncurses (toolchainlib)"
make install
report
ln -s libncursesw.a "${buildhome}/tools-prefix/${hosttriplet}/lib/libncurses.a" # Make it easier for configure scripts to find ncurses (some only look for the non-wide version)
ln -s libncursesw.so "${buildhome}/tools-prefix/${hosttriplet}/lib/libncurses.so"
cp "${buildhome}/tools-prefix/${hosttriplet}/include/ncurses/"* "${buildhome}/tools-prefix/${hosttriplet}/include" # Hack to make the toolchain conform to the system root
if "$sparse"; then cd ..; rm -rf *; fi

# Build bash
cd "${buildhome}/src"
report "download bash"
wgetwrapper http://ftp.gnu.org/gnu/bash/bash-4.2.tar.gz || wgetwrapper http://aos.ion.nu/sourcemirror/bash-4.2.tar.gz
report "unpack bash"
tar -xzf bash-4.2.tar.gz
report
cd bash-4.2
report "apply patches for bash"
for i in `seq -w 1 42`; do
  if [ "$i" = "03" ]; then sed -i -e "s/PATCHLEVEL 2/PATCHLEVEL 3/" patchlevel.h; continue; fi # 4.2.3 is broken
  patchfile="http://ftp.gnu.org/gnu/bash/bash-4.2-patches/bash42-0${i}"
  echo "Applying $patchfile"
  wget -q -O - "$patchfile" | patch -p0
done
report "" "noncritical" # Patches aren't important enough to warrant failing for lack of patch
mkdir build
cd build
report "configure bash"
../configure --prefix="/usr" --exec-prefix="" --host="$hosttriplet" --build="$buildtriplet" bash_cv_job_control_missing=available
report "build bash"
make -j"$makejobs" LIBS_FOR_BUILD='' # Doesn't mind -j#, LIBS_FOR_BUILD='' was added for FreeBSD because otherwise it would try to link a buildtime tool against -ldl
report "install bash"
make install DESTDIR="$buildroot"
report
if "$sparse"; then cd ..; rm -rf *; fi

# Build tar
cd "${buildhome}/src"
report "download tar"
wgetwrapper http://ftp.gnu.org/gnu/tar/tar-1.26.tar.xz || wgetwrapper http://aos.ion.nu/sourcemirror/tar-1.26.tar.xz
report "unpack tar"
tar -xJf tar-1.26.tar.xz
report
cd tar-1.26
mkdir build
cd build
report "configure tar"
../configure --prefix="/usr" --exec-prefix="" --host="$hosttriplet" --build="$buildtriplet"
report "build tar"
make -j"$makejobs" # Doesn't mind -j#
report "install tar"
make install DESTDIR="$buildroot"
report
if "$sparse"; then cd ..; rm -rf *; fi

# Build coreutils
cd "${buildhome}/src"
report "download coreutils"
wgetwrapper http://ftp.gnu.org/gnu/coreutils/coreutils-8.21.tar.xz || wgetwrapper http://aos.ion.nu/sourcemirror/coreutils-8.21.tar.xz
report "unpack coreutils"
tar -xJf coreutils-8.21.tar.xz
report
cd coreutils-8.21
mkdir build
cd build
report "configure coreutils"
../configure --prefix="/usr" --exec-prefix="" --host="$hosttriplet" --build="$buildtriplet" --enable-install-program="arch" fu_cv_sys_stat_statfs2_bsize=yes # configure does not detect some stat thing when crosscompiling, resulting in df not being built, so we provide it as a cache-variable
report
echo 'CFLAGS+=-DMB_LEN_MAX=16' >> Makefile # Workaround for the cross-toolchain somehow thinking MB_LEN_MAX is 1
sed -i -e '/man1_MANS *=/{s/=/= #/;}' Makefile # coreutils' man-pages are generated by running the executable with --help, which won't work when cross-compiling
report "build coreutils"
make -j"$makejobs" # Doesn't mind -j#
report "install coreutils"
make install DESTDIR="$buildroot"
report
if "$sparse"; then cd ..; rm -rf *; fi

# Build nettle
# Note: gnutls depends on nettle
cd "${buildhome}/src"
report "download nettle"
wgetwrapper http://ftp.gnu.org/gnu/nettle/nettle-2.7.tar.gz || wgetwrapper http://aos.ion.nu/sourcemirror/nettle-2.7.tar.gz
report "unpack nettle"
tar -xzf nettle-2.7.tar.gz
report
cd nettle-2.7
if "$nomath"; then
  sed -i -e 's|^#include <math|// &|' shadata.c
fi
mkdir build
cd build
report "configure nettle"
../configure --prefix="/usr" --host="$hosttriplet" --build="$buildtriplet"
report "build nettle"
make -j"$makejobs" # Doesn't mind -j#
report "install nettle"
make install DESTDIR="$buildroot"
report
mkdir ../build-toolchain
cd ../build-toolchain
report "configure nettle (toolchainlib)"
../configure --prefix="${buildhome}/tools-prefix/${hosttriplet}" --host="$hosttriplet" --build="$buildtriplet"
report "build nettle (toolchainlib)"
make -j"$makejobs" # Doesn't mind -j#
report "install nettle (toolchainlib)"
make install
report
if "$sparse"; then cd ..; rm -rf *; fi

# Build gnutls
cd "${buildhome}/src"
report "download gnutls"
wgetwrapper http://ftp.gnu.org/gnu/gnutls/gnutls-3.1.5.tar.xz || wgetwrapper http://aos.ion.nu/sourcemirror/gnutls-3.1.5.tar.xz
report "unpack gnutls"
tar -xJf gnutls-3.1.5.tar.xz
report
cd gnutls-3.1.5
mkdir build-toolchain
cd build-toolchain
report "configure gnutls (toolchainlib)"
../configure --prefix="${buildhome}/tools-prefix/${hosttriplet}" --host="$hosttriplet" --build="$buildtriplet" --without-libnettle-prefix --disable-crywrap --with-included-libtasn1 --without-p11-kit # crywrap (whatever that is, some proxy thing) references idna.h which is not available. all other flags prevent it from trying to build with libraries on the host
report "build gnutls (toolchainlib)"
make -j"$makejobs" # Doesn't mind -j#
report "install gnutls (toolchainlib)"
make install
report
cd .. # For some reason this build doesn't like separate build directories when building an x86_64 AOS on FreeBSD (wtf?)
report "configure gnutls"
./configure --prefix="/usr" --host="$hosttriplet" --build="$buildtriplet" --without-libnettle-prefix --disable-crywrap --with-included-libtasn1 --without-p11-kit # crywrap (whatever that is, some proxy thing) references idna.h which is not available. all other flags prevent it from trying to build with libraries on the host
report "build gnutls"
for x in `grep -rl '[-]L/usr/lib' . | grep -v libtool`; do sed -i -e 's|-L/usr/lib||g' "$x"; done # Work around poorly done buildsystem that throws in system paths when crosscompiling
sed -i -e 's/^shlibpath_var=.*/shlibpath_var=/' libtool # Prevent linking to stuff from the buildhost
# These new hacks are incredibly ugly, but seemingly necessary
sed -i -e '/inherit_rpath/n; /avoidtemprpath/n; s/rpath="[^"][^"]*"/rpath=" -L\/libtoolisbad "/g;s/rpath+="[^"][^"]*"/rpath=" -L\/libtoolisbad  "/' libtool
sed -i -e '/inherit_rpath/n; /avoidtemprpath/n; s/rpath=\\".*\\"/rpath=\\" -L\/libtoolisbad \\"/g;s/rpath+=\\".*\\"/rpath=\\" -L\/libtoolisbad  \\"/' libtool
sed -i -e '/error: cannot install/{s/func_fatal_error/echo/;}' libtool
make -j"$makejobs" # Doesn't mind -j#
report "install gnutls"
make install DESTDIR="$buildroot"
report
if "$sparse"; then rm -rf *; fi

# Build wget
cd "${buildhome}/src"
report "download wget"
wgetwrapper http://ftp.gnu.org/gnu/wget/wget-1.14.tar.xz || wgetwrapper http://aos.ion.nu/sourcemirror/wget-1.14.tar.xz
report "unpack wget"
tar -xJf wget-1.14.tar.xz
report
cd wget-1.14
mkdir build
cd build
report "configure wget"
../configure --prefix="/usr" --sysconfdir="/etc" --host="$hosttriplet" --build="$buildtriplet" --with-libgnutls-prefix="${buildhome}/tools-prefix/${hosttriplet}"
report "build wget"
make -j"$makejobs" # Doesn't mind -j#
report "install wget"
make install DESTDIR="$buildroot"
report
if "$sparse"; then cd ..; rm -rf *; fi

# Build net-tools
cd "${buildhome}/src"
report "download net-tools"
wgetwrapper http://downloads.sourceforge.net/project/net-tools/net-tools-1.60.tar.bz2 || wgetwrapper http://aos.ion.nu/sourcemirror/net-tools-1.60.tar.bz2
report "unpack net-tools"
tar -xjf net-tools-1.60.tar.bz2
report "configure net-tools"
cd net-tools-1.60
yes | make config CC="${hosttriplet}-gcc"
true > config.values
for sym in `sed -e 's/=.*//; s/^HAVE_\(AF\|HW\|\)//; s/INET6/IPV6/; s/net/NET/; s/TUNNEL/INET_&/; s/SIT/IPV6_&/; s/HDLCLAPB/LAPB/; s/^EC$/ECONET/; s/FW_/IP_NF_TARGET_/;' config.make`; do
  expr="CONFIG_${sym}\(\|NET\)[= ]"
  value="`grep "$expr" "${buildhome}/src/linux-3.11/.config"`"
  if [ "$sym" = "STRIP" -o "$sym" = "TR" ]; then value='n'; fi # This is no longer supported
  if [ "$value" = "" ]; then # No value in kernel config = use default
    echo >> config.values
  elif echo "$value" | grep -q '=[ym]'; then # Kernel supports it
    echo y >> config.values
  else # Kernel doesn't support it
    echo n >> config.values
  fi
done
make config CC="${hosttriplet}-gcc" < config.values
report
sed -i -e '/:$/{N;s/:\n.*}/: break;}/;}' lib/inet_sr.c # Tiny patch
sed -i -e '/:$/{N;s/:\n.*}/: break;}/;}' hostname.c
sed -i -e '/^[^"]*"[^"]*$/{:loop;/^[^"]*$/{s/^/"/;};s/$/\\n"/;n;/^[^"]*$/{b loop;};s/^/"/;}' mii-tool.c # How can you let something like this get released?...
sed -i -e '/#include </i#include <stddef.h>' lib/ec_hw.c # Needed for 'NULL'
report "build net-tools"
make CC="${hosttriplet}-gcc" AR="${hosttriplet}-ar" # Does mind -j#
report "install net-tools"
make install BASEDIR="$buildroot" CC="${hosttriplet}-gcc" AR="${hosttriplet}-ar"
report
if "$sparse"; then rm -rf *; fi

# Build gzip
cd "${buildhome}/src"
report "download gzip"
wgetwrapper http://ftp.gnu.org/gnu/gzip/gzip-1.6.tar.xz || wgetwrapper http://aos.ion.nu/sourcemirror/gzip-1.6.tar.xz
report "unpack gzip"
tar -xJf gzip-1.6.tar.xz
report
cd gzip-1.6
mkdir build
cd build
report "configure gzip"
../configure --prefix="/usr" --host="$hosttriplet" --build="$buildtriplet"
report "build gzip"
echo 'CFLAGS+=-DMB_LEN_MAX=16' >> Makefile # Workaround for the cross-toolchain somehow thinking MB_LEN_MAX is 1
echo 'CFLAGS+=-DMB_LEN_MAX=16' >> lib/Makefile
make -j"$makejobs" # Doesn't mind -j#
report "install gzip"
make install DESTDIR="$buildroot"
report
if "$sparse"; then cd ..; rm -rf *; fi

# Build bzip2
cd "${buildhome}/src"
report "download bzip2"
wgetwrapper http://www.bzip.org/1.0.6/bzip2-1.0.6.tar.gz || wgetwrapper http://aos.ion.nu/sourcemirror/bzip2-1.0.6.tar.gz
report "unpack bzip2"
tar -xzf bzip2-1.0.6.tar.gz
report
cd bzip2-1.0.6
sed -i -e '/^all:/s/\btest\b//;' Makefile # We're crosscompiling, we can't run tests
report "build bzip2"
make CC="${hosttriplet}-gcc -fPIC" AR="${hosttriplet}-ar" RANLIB="${hosttriplet}-ranlib" PREFIX="${buildroot}/usr"
report "install bzip2"
make CC="${hosttriplet}-gcc -fPIC" AR="${hosttriplet}-ar" RANLIB="${hosttriplet}-ranlib" PREFIX="${buildroot}/usr" install
report
if "$sparse"; then rm -rf *; fi

# Build xz
cd "${buildhome}/src"
report "download xz"
wgetwrapper http://tukaani.org/xz/xz-5.0.5.tar.xz || wgetwrapper http://aos.ion.nu/sourcemirror/xz-5.0.5.tar.xz
report "unpack xz"
tar -xJf xz-5.0.5.tar.xz
report
cd xz-5.0.5
mkdir build
cd build
report "configure xz"
../configure --prefix="/usr" --host="$hosttriplet" --build="$buildtriplet"
report "build xz"
make -j"$makejobs" # Doesn't mind -j#
report "install xz"
make install DESTDIR="$buildroot"
report
if "$sparse"; then cd ..; rm -rf *; fi

# Build dhcp
cd "${buildhome}/src"
report "download dhcp"
wgetwrapper http://ftp.isc.org/isc/dhcp/4.2.5/dhcp-4.2.5.tar.gz || wgetwrapper http://aos.ion.nu/sourcemirror/dhcp-4.2.5.tar.gz
report "unpack dhcp"
tar -xzf dhcp-4.2.5.tar.gz
report
cd dhcp-4.2.5
sed -i -e 's/\.\/configure /& --host="'"$hosttriplet"'" --build="'"$buildtriplet"'" BUILD_CC=gcc ac_cv_file__dev_random=yes /' bind/Makefile # Bad cross-build support
# Some fixes (I don't think these are problems with dhcp, but with the cross-toolchain)
sed -i -e 's/<limits\.h>/<linux\/limits\.h>/' client/dhclient.c
sed -i -e 's/<limits\.h>/<linux\/limits\.h>/' server/dhcpd.c
(cd bind; tar -xzf bind.tar.gz)
sed -i -e '/^gen:/{n;s/CC/BUILD_&/;s/${LIBS}//;}' bind/bind-9.8.4-P1/lib/export/dns/Makefile.in # Use the buildsystem native compiler for buildtime tool, and don't link to any unnecessary libraries
report "configure dhcp"
./configure --prefix="/usr" --sysconfdir="/etc" --host="$hosttriplet" --build="$buildtriplet" ac_cv_file__dev_random=yes # Can't check for /dev/random when cross-compiling
report "build dhcp"
make # Does mind -j#
report "install dhcp"
make install DESTDIR="$buildroot"
report
if "$sparse"; then rm -rf *; fi

# Build check (kbd dependency)
cd "${buildhome}/src"
report "download check"
wgetwrapper http://downloads.sourceforge.net/project/check/check/0.9.10/check-0.9.10.tar.gz || wgetwrapper http://aos.ion.nu/sourcemirror/check-0.9.10.tar.gz
report "unpack check"
tar -xzf check-0.9.10.tar.gz
cd check-0.9.10
mkdir -p build-toolchain
cd build-toolchain
report "configure check (toolchainlib)"
../configure --prefix="${buildhome}/tools-prefix/${hosttriplet}" --host="$hosttriplet" --build="$buildtriplet"
report "build check (toolchainlib)"
make -j"$makejobs" # Doesn't mind -j#
report "install check (toolchainlib)"
make install
mkdir -p ../build
cd ../build
report "configure check"
../configure --prefix="/usr" --host="$hosttriplet" --build="$buildtriplet"
report "build check"
make -j"$makejobs" # Doesn't mind -j#
report "install check"
make install DESTDIR="$buildroot"
report
if "$sparse"; then cd ..; rm -rf *; fi

# Build kbd
cd "${buildhome}/src"
report "download kbd"
wgetwrapper ftp://ftp.altlinux.org/pub/people/legion/kbd/kbd-2.0.0.tar.gz || wgetwrapper http://fossies.org/linux/misc/kbd-2.0.0.tar.gz || wgetwrapper http://aos.ion.nu/sourcemirror/kbd-2.0.0.tar.gz
report "unpack kbd"
tar -xzf kbd-2.0.0.tar.gz
report
cd kbd-2.0.0
mkdir build
cd build
report "configure kbd"
../configure --prefix="/usr" --host="$hosttriplet" --build="$buildtriplet" --disable-vlock # vlock requires PAM, not worth it
report "build kbd"
echo 'CFLAGS+=-DMB_LEN_MAX=16' >> src/libkeymap/Makefile # Workaround for the cross-toolchain somehow thinking MB_LEN_MAX is 1
make -j"$makejobs" # Doesn't mind -j#
report "install kbd"
make install DESTDIR="$buildroot"
report
if "$sparse"; then cd ..; rm -rf *; fi

# Build util-linux
cd "${buildhome}/src"
report "download util-linux"
wgetwrapper http://www.kernel.org/pub/linux/utils/util-linux/v2.23/util-linux-2.23.2.tar.xz || wgetwrapper http://aos.ion.nu/sourcemirror/util-linux-2.23.2.tar.xz
report "unpack util-linux"
tar -xJf util-linux-2.23.2.tar.xz
report
cd util-linux-2.23.2
mkdir build
cd build
report "configure util-linux"
../configure --prefix="/usr" --libdir="/lib${libsuffix}" --host="$hosttriplet" --build="$buildtriplet" --disable-wall --disable-login --disable-su CFLAGS="-DLINE_MAX=255 -I${buildhome}/tools-prefix/${hosttriplet}/include/ncursesw -D__user=" # wall requires chgrp which needs to run as root, and it's not important enough to require at this stage. A variant of login that doesn't require PAM is provided by shadow, avoid using the linux-specific __user macro
report "build util-linux"
make -j"$makejobs" # Doesn't mind -j#
report "install util-linux"
# Hack to keep libtool from linking to libraries from the buildhost
now="`date +'%m%d%H%M.%S'`"
for x in *.la*; do
  sed -i -e "s|^libdir=|&${buildroot}|" "$x"
  touch -t "$now" "$x"
done
sed -i -e '/^dependency_libs/{s/'"'"'$/ libcommon.la&/;}' libfdisk.la # Fix static library order issue
make install DESTDIR="$buildroot"
report
# Undo the hack once the install with the re-linking is done
sed -i -e "s|^libdir=${buildroot}|libdir=|" ${buildroot}/usr/lib/*.la
if "$sparse"; then cd ..; rm -rf *; fi

# Build sed
cd "${buildhome}/src"
report "download sed"
wgetwrapper http://ftp.gnu.org/gnu/sed/sed-4.2.2.tar.bz2 || wgetwrapper http://aos.ion.nu/sourcemirror/sed-4.2.2.tar.bz2
report "unpack sed"
tar -xjf sed-4.2.2.tar.bz2
report
cd sed-4.2.2
mkdir build
cd build
report "configure sed"
../configure --prefix="/usr" --host="$hosttriplet" --build="$buildtriplet" gl_cv_func_re_compile_pattern_working="yes"
report "build sed"
make -j"$makejobs" # Doesn't mind -j#
report "install sed"
make install DESTDIR="$buildroot"
report
if "$sparse"; then cd ..; rm -rf *; fi

# Build grep
cd "${buildhome}/src"
report "download grep"
wgetwrapper http://ftp.gnu.org/gnu/grep/grep-2.14.tar.xz || wgetwrapper http://aos.ion.nu/sourcemirror/grep-2.14.tar.xz
report "unpack grep"
tar -xJf grep-2.14.tar.xz
report
cd grep-2.14
mkdir build
cd build
report "configure grep"
../configure --prefix="/usr" --exec-prefix="" --host="$hosttriplet" --build="$buildtriplet"
report "build grep"
make -j"$makejobs" # Doesn't mind -j#
report "install grep"
make install DESTDIR="$buildroot"
report
if "$sparse"; then cd ..; rm -rf *; fi

# Build gawk
cd "${buildhome}/src"
report "download gawk"
wgetwrapper http://ftp.gnu.org/gnu/gawk/gawk-4.1.0.tar.xz || wgetwrapper http://aos.ion.nu/sourcemirror/gawk-4.1.0.tar.xz
report "unpack gawk"
tar -xJf gawk-4.1.0.tar.xz
report
cd gawk-4.1.0
sed -i -e '/Building the extensions is not/a\\texit 0; \\' extension/Makefile.in # The test won't work when crosscompiling
mkdir build
cd build
report "configure gawk"
../configure --prefix="/usr" --host="$hosttriplet" --build="$buildtriplet"
report "build gawk"
make -j"$makejobs" # Doesn't mind -j#
report "install gawk"
make install DESTDIR="$buildroot"
report
if "$sparse"; then cd ..; rm -rf *; fi

# Build make
cd "${buildhome}/src"
report "download make"
wgetwrapper http://ftp.gnu.org/gnu/make/make-3.81.tar.bz2 || wgetwrapper http://aos.ion.nu/sourcemirror/make-3.81.tar.bz2 # We use 3.81 instead of 3.82 since 3.82 seems to break a useful feature that is used by some projects
report "unpack make"
tar -xjf make-3.81.tar.bz2
report
cd make-3.81
mkdir build
cd build
report "configure make"
../configure --prefix="/usr" --host="$hosttriplet" --build="$buildtriplet"
report "build make"
make -j"$makejobs" # Doesn't mind -j#
report "install make"
make install DESTDIR="$buildroot"
report
if "$sparse"; then cd ..; rm -rf *; fi

# Build shadow
cd "${buildhome}/src"
report "download shadow"
wgetwrapper http://pkg-shadow.alioth.debian.org/releases/shadow-4.1.5.1.tar.bz2 || wgetwrapper http://aos.ion.nu/sourcemirror/shadow-4.1.5.1.tar.bz2
report "unpack shadow"
tar -xjf shadow-4.1.5.1.tar.bz2
report
cd shadow-4.1.5.1
mkdir build
cd build
report "configure shadow"
../configure --prefix="/usr" --exec-prefix="" --sysconfdir="/etc" --host="$hosttriplet" --build="$buildtriplet"
report "build shadow"
make -j"$makejobs" # Doesn't mind -j#
report "install shadow"
make install DESTDIR="$buildroot"
report
if "$sparse"; then cd ..; rm -rf *; fi

if ! "$skipwifi"; then
# Build libgpg-error (libgcrypt depends on it)
cd "${buildhome}/src"
report "download libgpg-error"
wgetwrapper ftp://ftp.gnupg.org/gcrypt/libgpg-error/libgpg-error-1.12.tar.bz2 || wgetwrapper http://mirrors.dotsrc.org/gcrypt/libgpg-error/libgpg-error-1.12.tar.bz2 || wgetwrapper http://aos.ion.nu/sourcemirror/libgpg-error-1.12.tar.bz2
report "unpack libgpg-error"
tar -xjf libgpg-error-1.12.tar.bz2
report
cd libgpg-error-1.12
mkdir build
cd build
report "configure libgpg-error"
../configure --prefix="/usr" --host="$hosttriplet" --build="$buildtriplet"
report "build libgpg-error"
make -j"$makejobs" # Doesn't mind -j#
report "install libgpg-error"
make install DESTDIR="$buildroot"
report
mkdir ../build-toolchain
cd ../build-toolchain
report "configure libgpg-error (toolchainlib)"
../configure --prefix="${buildhome}/tools-prefix/${hosttriplet}" --host="$hosttriplet" --build="$buildtriplet"
report "build libgpg-error (toolchainlib)"
make -j"$makejobs" # Doesn't mind -j#
report "install libgpg-error (toolchainlib)"
make install
report
if "$sparse"; then cd ..; rm -rf *; fi

# Build libgcrypt (wpa_supplicant depends on it)
cd "${buildhome}/src"
report "download libgcrypt"
wgetwrapper ftp://ftp.gnupg.org/gcrypt/libgcrypt/libgcrypt-1.5.3.tar.bz2 || wgetwrapper http://mirrors.dotsrc.org/gcrypt/libgcrypt/libgcrypt-1.5.3.tar.bz2 || wgetwrapper http://aos.ion.nu/sourcemirror/libgcrypt-1.5.3.tar.bz2
report "unpack libgcrypt"
tar -xjf libgcrypt-1.5.3.tar.bz2
report
cd libgcrypt-1.5.3
mkdir build
cd build
report "configure libgcrypt"
../configure --prefix="/usr" --host="$hosttriplet" --build="$buildtriplet" --with-gpg-error-prefix="${buildhome}/tools-prefix/${hosttriplet}" --disable-asm # the buildsystem can't handle asm while cross-compiling
report "build libgcrypt"
make -j"$makejobs" # Doesn't mind -j#
report "install libgcrypt"
make install DESTDIR="$buildroot"
report
mkdir ../build-toolchain
cd ../build-toolchain
report "configure libgcrypt (toolchainlib)"
../configure --prefix="${buildhome}/tools-prefix/${hosttriplet}" --host="$hosttriplet" --build="$buildtriplet" --with-gpg-error-prefix="${buildhome}/tools-prefix/${hosttriplet}" --disable-asm # the buildsystem can't handle asm while cross-compiling
report "build libgcrypt (toolchainlib)"
make -j"$makejobs" # Doesn't mind -j#
report "install libgcrypt (toolchainlib)"
make install
report
if "$sparse"; then cd ..; rm -rf *; fi

# Build libnl (wpa_supplicant depends on it)
cd "${buildhome}/src"
report "download libnl"
wgetwrapper http://www.infradead.org/~tgr/libnl/files/libnl-3.2.22.tar.gz || wgetwrapper http://aos.ion.nu/sourcemirror/libnl-3.2.22.tar.gz
report "unpack libnl"
tar -xzf libnl-3.2.22.tar.gz
report
cd libnl-3.2.22
sed -i -e '1i#include <linux/limits.h>' lib/route/qdisc/netem.c # minor patch (TODO: check if it's still necessary for 3.2.22)
mkdir build-toolchain
cd build-toolchain
report "configure libnl (toolchainlib)"
../configure --prefix="${buildhome}/tools-prefix/${hosttriplet}" --host="$hosttriplet" --build="$buildtriplet"
report "build libnl (toolchainlib)"
make -j"$makejobs" # Doesn't mind -j#
report "install libnl (toolchainlib)"
make install
report
mkdir ../build
cd ../build
report "configure libnl"
../configure --prefix="/usr" --sysconfdir="/etc" --host="$hosttriplet" --build="$buildtriplet"
report "build libnl"
# Ugly hacks to prevent linking to stuff from the buildhost
sed -i -e '/inherit_rpath/n; /avoidtemprpath/n; s/rpath="[^"][^"]*"/rpath=" -L\/libtoolisbad "/g;s/rpath+="[^"][^"]*"/rpath=" -L\/libtoolisbad  "/' libtool
sed -i -e '/inherit_rpath/n; /avoidtemprpath/n; s/rpath=\\".*\\"/rpath=\\" -L\/libtoolisbad \\"/g;s/rpath+=\\".*\\"/rpath=\\" -L\/libtoolisbad  \\"/' libtool
sed -i -e '/error: cannot install/{s/func_fatal_error/echo/;}' libtool
make -j"$makejobs" # Doesn't mind -j#
report "install libnl"
make install DESTDIR="$buildroot"
report
if "$sparse"; then cd ..; rm -rf *; fi

# Build wpa_supplicant
cd "${buildhome}/src"
report "download wpa_supplicant"
wgetwrapper http://hostap.epitest.fi/releases/wpa_supplicant-2.0.tar.gz || wgetwrapper http://aos.ion.nu/sourcemirror/wpa_supplicant-2.0.tar.gz
report "unpack wpa_supplicant"
tar -xzf wpa_supplicant-2.0.tar.gz
report
cd wpa_supplicant-2.0/wpa_supplicant
cp defconfig .config
echo 'CONFIG_TLS=gnutls' >> .config # we happen to have this installed already
echo 'CONFIG_LIBNL32=y' >> .config # seems to be required to know which version we're using
report "build wpa_supplicant"
sed -i -e 's/install -D /install /' Makefile # Not all versions of install accept -D, and the directories should already exist anyway
make CC="${hosttriplet}-gcc -I${buildhome}/tools-prefix/${hosttriplet}/include/libnl3" BINDIR="/usr/sbin" LIBDIR="/usr/lib" -j"$makejobs" # Doesn't mind -j#
report "install wpa_supplicant"
make install DESTDIR="$buildroot" BINDIR="/usr/sbin" LIBDIR="/usr/lib"
report
if "$sparse"; then cd ..; rm -rf *; fi
fi # ! $skipwifi

# Build module-init-tools
cd "${buildhome}/src"
report "download module-init-tools"
wgetwrapper http://kernel.org/pub/linux/utils/kernel/module-init-tools/module-init-tools-3.15.tar.xz || wgetwrapper http://aos.ion.nu/sourcemirror/module-init-tools-3.15.tar.xz
report "unpack module-init-tools"
tar -xJf module-init-tools-3.15.tar.xz
report
cd module-init-tools-3.15
mkdir build
cd build
report "configure module-init-tools"
../configure --prefix="/usr" --host="$hosttriplet" --build="$buildtriplet"
report "build module-init-tools"
make DOCBOOKTOMAN=no -j"$makejobs" # Doesn't mind -j#
report "install module-init-tools"
make install DOCBOOKTOMAN=no DESTDIR="$buildroot"
report
if "$sparse"; then cd ..; rm -rf *; fi

if ! "$skipwifi"; then
# Build wireless-tools
cd "${buildhome}/src"
report "download wireless-tools"
wgetwrapper http://www.hpl.hp.com/personal/Jean_Tourrilhes/Linux/wireless_tools.29.tar.gz || wgetwrapper http://aos.ion.nu/sourcemirror/wireless_tools.29.tar.gz
report "unpack wireless-tools"
tar -xzf wireless_tools.29.tar.gz
report
cd wireless_tools.29
report "build wireless-tools"
make PREFIX="/usr" CC="${hosttriplet}-gcc" -j"$makejobs" # Doesn't mind -j#
report "install wireless-tools"
make PREFIX="${buildroot}/usr" CC="${hosttriplet}-gcc" install
report
if "$sparse"; then rm -rf *; fi
fi # ! $skipwifi

# Build file
cd "${buildhome}/src"
report "unpack file"
tar -xzf file-5.14.tar.gz
report "configure file"
cd file-5.14
mkdir build
cd build
# I haven't investigated why, but if file thinks glibc's mmap isn't working file will segfault at the end. Configure can't check if it's working when cross-compiling, so we tell it it's working through a cache value
../configure --prefix="/usr" --host="$hosttriplet" --build="$buildtriplet" ac_cv_func_mmap_fixed_mapped=yes
report "build file"
make PATH="${buildhome}/tools-prefix/bin:$PATH" -j"$makejobs" # Doesn't mind -j# and needs to have native file-5.14 found first in PATH
report "install file"
make install DESTDIR="$buildroot"
report
if "$sparse"; then cd ..; rm -rf *; fi

# Build diffutils
cd "${buildhome}/src"
report "download diffutils"
wgetwrapper http://ftp.gnu.org/gnu/diffutils/diffutils-3.3.tar.xz || wgetwrapper http://aos.ion.nu/sourcemirror/diffutils-3.3.tar.xz
report "unpack diffutils"
tar -xJf diffutils-3.3.tar.xz
report
cd diffutils-3.3
mkdir build
cd build
report "configure diffutils"
../configure --prefix="/usr" --host="$hosttriplet" --build="$buildtriplet"
report "build diffutils"
make -j"$makejobs" # Doesn't mind -j#
report "install diffutils"
make install DESTDIR="$buildroot"
report
if "$sparse"; then cd ..; rm -rf *; fi

# Build less
cd "${buildhome}/src"
report "download less"
wgetwrapper http://ftp.gnu.org/gnu/less/less-451.tar.gz || wgetwrapper http://aos.ion.nu/sourcemirror/less-451.tar.gz
report "unpack less"
tar -xzf less-451.tar.gz
report
cd less-451
mkdir build
cd build
report "configure less"
../configure --prefix="/usr" --host="$hosttriplet" --build="$buildtriplet"
report "build less"
make -j"$makejobs" # Doesn't mind -j#
report "install less"
make install DESTDIR="$buildroot"
report
if "$sparse"; then cd ..; rm -rf *; fi

# Build which
cd "${buildhome}/src"
report "download which"
wgetwrapper http://ftp.gnu.org/gnu/which/which-2.20.tar.gz || wgetwrapper http://aos.ion.nu/sourcemirror/which-2.20.tar.gz
report "unpack which"
tar -xzf which-2.20.tar.gz
report
cd which-2.20
mkdir build
cd build
report "configure which"
../configure --prefix="/usr" --host="$hosttriplet" --build="$buildtriplet"
report "build which"
make -j"$makejobs" # Doesn't mind -j#
report "install which"
make install DESTDIR="$buildroot"
report
if "$sparse"; then cd ..; rm -rf *; fi

# Build findutils
cd "${buildhome}/src"
report "download findutils"
wgetwrapper http://alpha.gnu.org/gnu/findutils/findutils-4.5.10.tar.gz || wgetwrapper http://aos.ion.nu/sourcemirror/findutils-4.5.10.tar.gz # Latest non-alpha failed to be cross-compiled, but alpha works
report "unpack findutils"
tar -xzf findutils-4.5.10.tar.gz
report
cd findutils-4.5.10
mkdir build
cd build
report "configure findutils"
../configure --prefix="/usr" --localstatedir="/var" --host="$hosttriplet" --build="$buildtriplet"
report "build findutils"
make -j"$makejobs" # Doesn't mind -j#
report "install findutils"
make install DESTDIR="$buildroot"
report
if "$sparse"; then cd ..; rm -rf *; fi

if ! "$skipwifi"; then
# Build iw
cd "${buildhome}/src"
report "download iw"
wgetwrapper https://www.kernel.org/pub/software/network/iw/iw-3.11.tar.xz || wgetwrapper http://aos.ion.nu/sourcemirror/iw-3.11.tar.xz
report "unpack iw"
tar -xJf iw-3.11.tar.xz
cd iw-3.11
report "build iw"
make CC="${hosttriplet}-gcc" -j"$makejobs" # Doesn't mind -j#
report "install iw"
make install DESTDIR="$buildroot"
report
if "$sparse"; then rm -rf *; fi
fi # ! $skipwifi

cd "$buildhome"

# Make an init, maybe just a simple shell script?
mkdir -p "${buildroot}/sbin"
report "write /sbin/init"
cat > "${buildroot}/sbin/init" << "EOF"
#!/bin/sh
# I believe init systems tend to be way more complicated than they need to be, so here's a simple one consisting of just one script, feel free to modify it

trap '' SIGINT # Don't accidentally kill init
if [ "$1" = "shell" ]; then while true; do bash; done; fi # You may wish to replace bash with login

hostname "`cat /etc/hostname`"
mount -t devtmpfs none /dev 2> /dev/null # Just in case we're not mounting the root directly
mkdir -p /dev/pts
mount -t devpts none /dev/pts
true > /dev/initctl
chmod 600 /dev/initctl
mount -t proc none /proc
mount -t sysfs none /sys
mount / -o remount,rw
export PATH="/bin:/sbin:/usr/bin:/usr/sbin"
export HOME="/root"
ifconfig lo up # Bring up the loopback interface
sendsysrq()
{
  while [ "$#" -gt "0" ]; do
    echo "$1" > /proc/sysrq-trigger
    if [ "$1" = "u" ]; then sleep 3
    elif [ "$1" != "r" ]; then sleep 1; fi
    shift
  done
}
/etc/initservices.sh > /dev/null 2> /dev/null &

cat /etc/motd
export HOME="/root"
openvt -c 1 -f /sbin/init shell
openvt -c 2 /sbin/init shell
openvt -c 3 /sbin/init shell
openvt -c 4 /sbin/init shell
openvt -c 5 /sbin/init shell
openvt -c 6 /sbin/init shell
while true; do # Just sleep and check for commands in /dev/initctl
  sleep 1
  if grep -q poweroff /dev/initctl; then
    sendsysrq r e i s u o # o = powerOff
  elif grep -q reboot /dev/initctl; then
    sendsysrq r e i s u b # b = reBoot
  fi
done
EOF
report
chmod +x "${buildroot}/sbin/init"

report "write /etc/initservices.sh"
echo '#!/bin/sh' > "${buildroot}/etc/initservices.sh"
chmod +x "${buildroot}/etc/initservices.sh"
echo '# In this file you can add commands to automatically start services at boot time.' >> "${buildroot}/etc/initservices.sh"
echo '# Note that this file is only used for the basic default init in AOS, if you use another init system this file is no longer used.' >> "${buildroot}/etc/initservices.sh"
echo '# Also note that commands in this file need to daemonize or be backgrounded, otherwise subsequent commands will not run.' >> "${buildroot}/etc/initservices.sh"

report "write /sbin/poweroff"
cat > "${buildroot}/sbin/poweroff" << "EOF"
#!/bin/sh
echo 'poweroff' > /dev/initctl
EOF
report
chmod +x "${buildroot}/sbin/poweroff"

report "write /sbin/reboot"
cat > "${buildroot}/sbin/reboot" << "EOF"
#!/bin/sh
echo 'reboot' > /dev/initctl
EOF
report
chmod +x "${buildroot}/sbin/reboot"

report "write /sbin/shutdown"
cat > "${buildroot}/sbin/shutdown" << "EOF"
#!/bin/sh
# TODO: make this more compatible with sysvinit's shutdown
if [ "$1" = "-r" ]; then
  reboot
elif [ "$1" = "-h" ]; then
  poweroff
fi
EOF
report
chmod +x "${buildroot}/sbin/shutdown"

# Make a firmware loader, apparently linux calls a userspace application for that now
report "write /sbin/hotplug"
mkdir -p "${buildroot}/sbin"
cat > "${buildroot}/sbin/hotplug" << "EOF"
#!/bin/sh
echo 1 > "/sys/${DEVPATH}/loading"
cat "/lib/firmware/${FIRMWARE}" > "/sys/${DEVPATH}/data"
echo 0 > "/sys/${DEVPATH}/loading"
EOF
report
chmod +x "${buildroot}/sbin/hotplug"

# Make a dhclient-script too, which ISC really should have included with the dhcp package
report "write /sbin/dhclient-script"
cat > "${buildroot}/sbin/dhclient-script" << "EOF"
#!/bin/sh
if [ "$reason" = "PREINIT" ]; then
  ifconfig "$interface" up
elif [ "$reason" = "MEDIUM" ]; then
  true # I'm not sure what 'MEDIUM' means here
elif [ "$reason" = "REBOOT" -o "$reason" = "BOUND" -o "$reason" = "RENEW" ]; then # codewords for Set configuration
  ifconfig "$interface" "$new_ip_address" netmask "$new_subnet_mask" broadcast "$new_broadcast_address"
  while route del default 2> /dev/null; do continue; done
  for route in $new_routers; do
    route add default gw "$route"
  done
  true > /etc/resolv.conf
  if [ "$new_domain_name" != "" ]; then echo "search ${new_domain_name}" >> /etc/resolv.conf; fi
  for ns in $new_domain_name_servers; do
    echo "nameserver $ns" >> /etc/resolv.conf
  done
fi
EOF
report
chmod +x "${buildroot}/sbin/dhclient-script"

# This is used for the final output, but we might as well track the files down before we copy more files into the mix (parent-src)
suidfiles="`find root/ -perm /7000 -and -type f 2> /dev/null || find root/ -perm +7000 -and -type f`" # GNU suggests using / instead of +, but FreeBSD's find returns error on /

mkdir -p "${buildroot}/usr/parent-src"
if "$sparse"; then
  report "copy linux source-tree to /usr/parent-src"
  cp -r "$buildhome"/src/linux-3.11 "${buildroot}/usr/parent-src"
  report "" "noncritical" # Failing here is not worth it, especially since some implementations of cp return non-zero for previous warnings
  rm -rf "$buildhome"/src/*/ "$buildhome"/tools-src
else
  # Copy crosscompiled source-directories to the new root
  report "copy sources to /usr/parent-src"
  cp -r "$buildhome"/src/* "${buildroot}/usr/parent-src"
  report "" "noncritical" # Failing here is not worth it, especially since some implementations of cp return non-zero for previous warnings
  echo "These are the sources used to build this system, including configurations for building them on the build host." > "${buildroot}/usr/parent-src/README"
fi

# Make a motd
mkdir -p "${buildroot}/etc"
report "write /etc/motd"
cat > "${buildroot}/etc/motd" << "EOF"
Welco[04mme[00m_to     ___     _____
    /   \    /´ _ `\  /  ___)
   /  _  \  /  / \  \|  (__
  /  /_\  \|  (   )  |\__  \
 /   ___   \\  \_/  / ___)  |
/___/   \___\\,___,/ (_____/
          GNU+Linux
EOF

# Other little tweaks
report "fix paths of libtool libraries"
for lafile in "${buildroot}/usr/lib/"*.la "${buildroot}/lib/"*.la "${buildroot}/usr/lib64/"*.la "${buildroot}/lib64/"*.la; do
  if [ ! -e "$lafile" ]; then continue; fi # No .la file in that directory
  sed -i -e 's|-L/libtoolisbad|/usr/lib|g;' "$lafile" # Clean up after our libtool workaround
  echo "Fixing $lafile" | sed -e "s@${buildroot}@@"
  olddepline="`grep '^dependency_libs=' "$lafile"`"
  expr="s/ -L[^ ']*//;"
  newdepline="`echo "$olddepline" | sed -e "$expr"`" # clear any -L paths, these libs should all be installed in standard search paths
  for arg in `echo "$newdepline" | sed -e "s/^dependency_libs=' //;s/'//;s/ /\n/g;"`; do
    if echo "$arg" | grep -q '\.la$'; then
      lib="`echo "$arg" | sed -e 's@.*/@@'`"
      if [ -e "${buildroot}/lib/${lib}" ]; then
        expr="s@ ${arg}@ /lib/${lib}@g"
        newdepline="`echo "$newdepline" | sed -e "$expr"`"
      elif [ -e "${buildroot}/usr/lib/${lib}" ]; then
        expr="s@ ${arg}@ /usr/lib/${lib}@g"
        newdepline="`echo "$newdepline" | sed -e "$expr"`"
      elif [ -e "${buildroot}/lib64/${lib}" ]; then
        expr="s@ ${arg}@ /lib64/${lib}@g"
        newdepline="`echo "$newdepline" | sed -e "$expr"`"
      elif [ -e "${buildroot}/usr/lib64/${lib}" ]; then
        expr="s@ ${arg}@ /usr/lib64/${lib}@g"
        newdepline="`echo "$newdepline" | sed -e "$expr"`"
      else
        echo "WARNING: can't find referenced library ${lib}"
      fi
    fi
  done
  if [ "$olddepline" != "$newdepline" ]; then
    echo "Replacing this: $olddepline"
    echo "With this:      $newdepline"
    sed -i -e "s@^${olddepline}@${newdepline}@" "$lafile"
  fi
done
report "write /etc/passwd"
echo "root:x:0:0:root:/root:/bin/sh" > "${buildroot}/etc/passwd"
report "enable password encryption in /etc/login.defs"
echo "ENCRYPT_METHOD SHA512" >> "${buildroot}/etc/login.defs"
report "write /etc/group"
echo "root:x:0:" > "${buildroot}/etc/group"
report "write /etc/hostname"
echo "`whoami`-AOS" > "${buildroot}/etc/hostname"
report "write /etc/nsswitch.conf"
echo "hosts:          files dns [!UNAVAIL=return]" > "${buildroot}/etc/nsswitch.conf"
report "write /etc/hosts"
echo "127.0.0.1	localhost `whoami`-AOS" > "${buildroot}/etc/hosts"
report "symlink sh to bash"
ln -s bash "${buildroot}/bin/sh"
report "symlink cc to gcc"
ln -s gcc "${buildroot}/usr/bin/cc"
report "symlink /lib/cpp to /usr/bin/cpp"
ln -s "/usr/bin/cpp" "${buildroot}/lib/cpp" # some silly conventions
ln -s "/bin/env" "${buildroot}/usr/bin/env"
report "create /proc directory"
mkdir -p "${buildroot}/proc"
report "create /sys directory"
mkdir -p "${buildroot}/sys"
report "create /dev directory"
mkdir -p "${buildroot}/dev"
report "create /tmp directory"
mkdir -p "${buildroot}/tmp"
chmod 1777 "${buildroot}/tmp"
report "create /root directory"
mkdir -p "${buildroot}/root"
chmod 700 "${buildroot}/root"
report "create /var/db directory"
mkdir -p "${buildroot}/var/db" # needed by dhclient
report "create /var/run directory"
mkdir -p "${buildroot}/var/run" # needed by dhclient and lots of different apps that background themselves
report "symlink /etc/mtab to /proc/mounts"
mkdir -p "${buildroot}/etc"
ln -s /proc/mounts "${buildroot}/etc/mtab" # Easier than trying to maintain an actual file
report "create /home directory"
mkdir -p "${buildroot}/home"
report "create /usr/src directory"
mkdir -p "${buildroot}/usr/src"
chmod 1777 "${buildroot}/usr/src"
report "create /var/spool/mail"
mkdir -p "${buildroot}/var/spool/mail"
report "create /etc/profile"
echo 'export PATH="/bin:/sbin:/usr/bin:/usr/sbin"' > "${buildroot}/etc/profile"
report "symlink /usr/parent-src/linux-3.11 to /usr/src/linux" # For building external kernel modules
ln -s "/usr/parent-src/linux-3.11" "${buildroot}/usr/src/linux"
report "fetch SSL/TLS CAs"
mkdir -p "${buildroot}/etc/ssl/certs"
(cd "${buildroot}/etc/ssl/certs"
wget --no-check-certificate \
http://www.cacert.org/certs/root.crt \
http://www.cacert.org/certs/class3.crt \
https://www.digicert.com/CACerts/DigiCertGlobalCA2048.crt \
https://www.digicert.com/CACerts/DigiCertGlobalCA.crt \
https://www.digicert.com/CACerts/DigiCertHighAssuranceEVCA-1.crt \
https://www.digicert.com/CACerts/DigiCertAssuredIDCA-1.crt \
https://www.digicert.com/CACerts/DigiCertGlobalCA-1.crt \
https://www.digicert.com/CACerts/DigiCertAssuredIDCodeSigningCA-1.crt \
https://www.digicert.com/CACerts/DigiCertHighAssuranceCodeSigningCA-1.crt \
https://www.entrust.net/downloads/binary/entrust_ssl_ca.cer \
https://www.entrust.net/downloads/binary/entrust_l1e.cer \
https://www.entrust.net/downloads/binary/entrust_l1c.cer \
https://www.entrust.net/downloads/binary/entrust_l1e_sha2.cer \
https://www.entrust.net/downloads/binary/entrust_l1c_sha2.cer \
https://www.verisign.com/repository/roots/root-certificates/PCA-3G2.pem \
https://www.verisign.com/repository/roots/root-certificates/PCA-3.pem \
https://www.verisign.com/repository/roots/root-certificates/PCA-3G5.pem \
https://www.verisign.com/repository/roots/root-certificates/PCA-3G3.pem \
https://www.verisign.com/repository/roots/root-certificates/PCA-3G4.pem \
https://www.verisign.com/repository/roots/root-certificates/PCA-2G3.pem \
https://www.verisign.com/repository/roots/root-certificates/PCA-2G2.pem \
https://www.verisign.com/repository/roots/root-certificates/PCA-1.pem \
https://www.verisign.com/repository/roots/root-certificates/PCA-1G3.pem \
https://www.verisign.com/repository/roots/root-certificates/PCA-universal.pem \
https://www.verisign.com/repository/roots/root-certificates/PCA-4G3.pem \
https://www.verisign.com/repository/roots/root-certificates/PCA_1_G6.pem \
https://www.verisign.com/repository/roots/root-certificates/PCA_2_G6.pem \
http://www.geotrust.com/resources/root_certificates/certificates/Equifax_Secure_Certificate_Authority.pem \
http://www.geotrust.com/resources/root_certificates/certificates/GeoTrust_Global_CA.pem \
http://www.geotrust.com/resources/root_certificates/certificates/GeoTrust_Primary_CA.pem \
https://www.thawte.com/roots/thawte_Primary_Root_CA.pem \
https://www.thawte.com/roots/thawte_Premium_Server_CA.pem \
https://www.thawte.com/roots/thawte_Server_CA.pem \
https://www.thawte.com/roots/thawte_Primary_Root_CA-G2_ECC.pem \
https://www.thawte.com/roots/thawte_Primary_Root_CA-G3_SHA256.pem \
https://www.thawte.com/roots/thawte_Personal_Freemail_CA.pem \
http://certificates.godaddy.com/repository/gdroot-g2.crt \
http://certificates.godaddy.com/repository/gd-class2-root.crt \
http://certificates.godaddy.com/repository/ca_bundle.crt \
http://certificates.starfieldtech.com/repository/sfroot-g2.crt \
http://certificates.starfieldtech.com/repository/sfsroot-g2.crt \
https://www.cybertrust.ne.jp/SureServer/file/root_ca/BCTRoot.txt \
http://www.startssl.com/certs/ca-bundle.pem)
for ca in "${buildroot}/etc/ssl/certs/"*; do
  if ! grep -q '^----*BEGIN' "$ca"; then # If they are in binary format then turn them into the common base64 format
    openssl x509 -inform der -in "$ca" -out tmpconvert 2> /dev/null
    rm -f "$ca"
    mv tmpconvert "$ca" 2> /dev/null
  fi
  echo >> "$ca" # Add a newline to each file to avoid messed up CAs during concatenation
done
cat "${buildroot}/etc/ssl/certs/"* > "${buildroot}/etc/ssl/certs/ca-certificates.crt"
report "" "noncritical" # Even if we don't get the CA certificates it'll be a fairly complete system, just pass --no-check-certificate to wget

report "write a grub config"
# Note: this is only an assumption, and probably doesn't work on all platforms yet
rootdev="`df -h "$buildroot" | tail -n 1 | sed -e 's/ .*//'`"
grubroot="`echo "$rootdev" | sed -e 's|.*/||;s/^[hs]d//;'`"
grubroot="(hd`echo "$grubroot" | sed -e 'y/abcdefghij/0123456789/;s/^./&,/;'`)"
mkdir -p "${buildroot}/boot/grub"
cat > "${buildroot}/boot/grub/grub.cfg" << END
load vbe
load gfxmenu
load vga
load video
set timeout=10
menuentry AOS {
  set root=${grubroot}
  linux /boot/vmlinuz-${linuxversion} root=${rootdev} quiet
}
END

report "generate locales"
mkdir -p "${buildroot}/lib/locale"
# Workaround for buildhosts with different localedef paths
localedefpath="`which localedef`"
altpath="`strings "$localedefpath" | grep '\/locale$' | head -n 1`"
ln -s "${buildroot}/lib/locale" "${buildroot}/${altpath}"
gzip -dc "${buildroot}/usr/share/i18n/charmaps/UTF-8.gz" > /tmp/UTF-8
for locale in `ls "${buildroot}/usr/share/i18n/locales"`; do
  localedef --prefix="$buildroot" -i "${buildroot}/usr/share/i18n/locales/${locale}" -f /tmp/UTF-8 "${locale}.UTF-8"
done
report "" "noncritical" # Failing this is bad, but not worth failing the whole build over
rm -f /tmp/UTF-8 "${buildroot}/${altpath}" 2> /dev/null
# Set a locale
echo "The following locales were generated:"
# TODO: skip iso*, translit_* and POSIX?
ls "${buildroot}/usr/share/i18n/locales"
printf "Pick a locale for your system (or blank for en_US): "
read locale
if [ "$locale" = "" ]; then locale="en_US"; fi
while [ ! -e "${buildroot}/usr/share/i18n/locales/${locale}" ]; do
  ls "${buildroot}/usr/share/i18n/locales"
  printf "Pick a locale for your system (or blank for en_US): "
  read locale
  if [ "$locale" = "" ]; then locale="en_US"; fi
done
echo "export LC_ALL='${locale}.UTF-8'" >> "${buildroot}/etc/profile"
sed -i -e "/export PATH/iexport LC_ALL='${locale}.UTF-8'" "${buildroot}/sbin/init"

echo "Done!"
echo "You should now run chown -R 0.0 root/"
if [ "$suidfiles" != "" ]; then
  echo "You will also need to run the following command(s) afterwards to restore suid for some programs"
  for prog in $suidfiles; do
    echo "chmod `stat -c '%a' "$prog" 2> /dev/null || stat -f '%Mp%Lp' "$prog"` $prog" # Fallback for alternative implementations of stat
  done
fi
# TODO:
# Build grub (not sure if this is a good idea.. maybe to make sure it's a known grub version and that the config will work? either way it's to be run on the host system, maybe build it for the target too for mkconfig stuff)
# Install grub, something like grub-install --boot-directory=/media/<UUID or something>/boot /dev/sdb
# Make a default grub config
# Make an initrd that can find roots based on UUID, also how does pivot_root work? util-linux's findfs can find partitions based on UUID, or mount -U $uuid

# Find out UUID of disks:
# for x in /dev/disk/by-uuid/*; do echo -n "${x}: "; readlink -f "$x"; done
# better: blkid
