#! /usr/bin/env bash
set -e
if [[ 0 == `id -u` ]]; then
    # set -x
    export DEBIAN_FRONTEND=noninteractive
    apt_cache_tar=/vagrant/var_cache_apt.tar
    tar_cmd=c
    if [[ -f   $apt_cache_tar ]]; then
      tar -xvf $apt_cache_tar -C /
      tar_cmd=u
    fi
    apt-get update
    _apt_get() {
      for i in 1 2 3; do
          apt-get "$@" && return 0
      done
      return 1
    }
    # set them to download first, then install them
    apt_extra='-d'
    for x in 1 2; do
      if [[ $x == 2 ]]; then
        cd /
        tar -${tar_cmd}vf $apt_cache_tar var/cache/apt var/lib/dpkg var/lib/apt
      fi
      _apt_get --no-install-recommends install -y \
        $apt_extra \
        autoconf automake bash bison bzip2 diffutils file flex g++ gawk \
        gcc-multilib gettext gperf groff-base libncurses-dev libexpat1-dev \
        libslang2 libssl-dev libtool libxml-parser-perl make patch perl pkg-config \
        python sed shtool tar texinfo unzip zlib1g zlib1g-dev \
        git-core \
        libstdc++6 automake1.11 intltool autopoint \
        libelf-dev:i386 libelf1:i386
      apt_extra=''
    done
    echo '==='
    echo '=== Switching to the vagrant user for the build...'
    echo '==='
    exec sudo -i -u vagrant bash -x "$0" "$@"
fi

VER="${1:-380.69}"

cd ~vagrant

# set this so the git info will be available to "make"
export GIT_DIR=/vagrant/.git
if [[ ! -d "$GIT_DIR" ]]; then
  echo "EGAD, git-dir \"$GIT_DIR\" is 404" >&2
  exit 1
fi

mkdir -p asuswrt-merlin
cd asuswrt-merlin

cp /vagrant/build.sh .

git checkout --force $VER
git reset --hard $VER
ls -la
# we have to disown this since this script is running in :provision
nohup bash -xc "./build.sh &>build-${VER}.out" &
ls -la
ps -efw
disown