#!/bin/bash

set -e

TARGET=$1

# packages
sudo apt-get update
sudo apt-get install -y --no-install-recommends \
  automake \
  bison \
  bzip2 \
  ca-certificates \
  cmake \
  curl \
  file \
  flex \
  g++ \
  gawk \
  gdb \
  git \
  gperf \
  help2man \
  libncurses-dev \
  libssl-dev \
  libtool-bin \
  make \
  patch \
  pkg-config \
  python3 \
  rsync \
  texinfo \
  unzip \
  wget \
  xz-utils

# patch
pushd builder
git reset --hard HEAD
git clean -fd
for i in ../targets/${TARGET}/*; do
    if [[ $i == *.patch ]]; then
        patch -Np1 -i $i
    fi
done
popd

# crosstool-ng
sudo mkdir -p /opt
sudo chmod 0777 /opt
sudo rm -rf /opt/ct-ng
pushd builder
./bootstrap
./configure --prefix=/opt/ct-ng
make -j`nproc`
sudo make install
popd

# build
rm -rf build
mkdir -p build
cp targets/${TARGET}/config build/.config
pushd build
/opt/ct-ng/bin/ct-ng olddefconfig
/opt/ct-ng/bin/ct-ng build
popd

# tarball
sudo mv /opt/x-tools/${TARGET} .
sudo chown -R root:root ${TARGET}
sudo tar -cJvf ${TARGET}.tar.xz ${TARGET}
sudo sha256sum ${TARGET}.tar.xz | awk '{ print $1 }' > ${TARGET}.tar.xz.sha256
