#!/usr/bin/env bash
set -eu

if [ ! -v SCRIPTS_DIR ]; then
  SCRIPTS_DIR=$(cd $(dirname $0);pwd)
fi

if [ ! -v WORK_DIR ]; then
  WORK_DIR=$HOME/workdir
fi

SSP_DIR=$WORK_DIR/ssp
SSP_PACKAGE=ssp-1.3.0.tar.gz
SSP_DOWNLOAD_URL=https://www.toppers.jp/download.cgi/$SSP_PACKAGE
SSP_TARGET_NAME=cq_frk_fm3_gcc

ASP3_DIR=$WORK_DIR/asp3
ASP3_PACKAGE=asp3-3.1.0.tar.gz
ASP3_DOWNLOAD_URL=https://www.toppers.jp/download.cgi/$ASP3_PACKAGE


: "setup tools (compiler, emulator, etc.)" && {
  $SCRIPTS_DIR/setup_tools.sh
  . $HOME/.profile
}

: "Download TOPPERS/ASP3 package to get a configurator files"  && {
  cd $WORK_DIR
  if [ ! -e $ASP3_DIR ]; then
    if [ ! -e $ASP3_PACKAGE ]; then
      curl $ASP3_DOWNLOAD_URL -o $ASP3_PACKAGE
    fi
    tar xvf $ASP3_PACKAGE
  fi
}

: "if ssp directory already exists, rename it and create new directory" && {
  cd $WORK_DIR
  if [ -e $SSP_DIR ]; then
    mv $SSP_DIR $SSP_DIR.$(date +%Y%m%d_%H%M%S)
  fi

  if [ ! -e $SSP_PACKAGE ]; then
    curl $SSP_DOWNLOAD_URL -o $SSP_PACKAGE
  fi

  mkdir $SSP_DIR
  tar xvf $SSP_PACKAGE -C $SSP_DIR --strip-components 2
}

: "setup source code(convert to UTF8, patch, etc.)" && {
  for i in `find $SSP_DIR -type f` ; do nkf --overwrite --oc=UTF-8 $i; done
  cp -a $ASP3_DIR/sample/Makefile $SSP_DIR/sample

  $SCRIPTS_DIR/install.sh $SSP_DIR

  cd $SSP_DIR
  ln -s $ASP3_DIR/configure.rb configure.rb
  ln -s $ASP3_DIR/cfg cfg
}

: "build a kernel" && {
  cd $SSP_DIR
  if [ -e build ]; then
    mv build build.$(date +%Y%m%d_%H%M%S)
  fi
  mkdir build
  cd build
  ../configure.rb -T $SSP_TARGET_NAME -w
  make
}

exit 0
