#!/bin/bash

ARGUMENTS="$@"
CWD=$(pwd)
# https://stackoverflow.com/questions/59895/getting-the-source-directory-of-a-bash-script-from-within
DIRNAME="$(dirname "$(readlink -f "$0")")"

# with help from https://stackoverflow.com/a/29754866,

# saner programming env: these switches turn some bugs into errors
set -o errexit -o pipefail -o noclobber -o nounset

! getopt --test > /dev/null 
if [[ ${PIPESTATUS[0]} -ne 4 ]]; then
    echo "Sorry, `getopt --test` failed in this environment."
    exit 1
fi

OPTIONS=hdtci:o:n:a
LONGOPTS=help,docker,no-cache,target:,input:,output:,name:,arch:,target-version:,debian-release:

# -use ! and PIPESTATUS to get exit code with errexit set
# -temporarily store output to be able to check for errors
# -activate quoting/enhanced mode (e.g. by writing out “--options”)
# -pass arguments only via   -- "$@"   to separate them correctly
! PARSED=$(getopt --options=$OPTIONS --longoptions=$LONGOPTS --name "$0" -- "$@")
if [[ ${PIPESTATUS[0]} -ne 0 ]]; then
    # e.g. return value is 1
    #  then getopt has complained about wrong arguments to stdout
    exit 2
fi
# read getopt’s output this way to handle the quoting right:
eval set -- "$PARSED"

HELP=n DOCKER=n
TARGET=- INPUT=- OUTPUT=- NAME=- ARCH=-

while true; do
    case "$1" in
        -h|--help)
            HELP=y
            shift
            ;;
        -d|--docker)
            DOCKER=y
            shift
            ;;
        --no-cache)
            shift
            ;;
        -t|--target)
            TARGET="$2"
            shift 2
            ;;
        -i|--input)
            INPUT="$2"
            shift 2
            ;;
        -o|--output)
            OUTPUT="$2"
            shift 2
            ;;
        -n|--name)
            NAME="$2"
            shift 2
            ;;
        -a|--arch)
            ARCH="$2"
            shift 2
            ;;
        --target-version)
            shift 2
            ;;
        --debian-release)
            shift 2
            ;;
        --)
            shift
            break
            ;;
        *)
            echo "Programming error"
            exit 3
            ;;
    esac
done

if
  [ "${HELP}" == "y" ] || \
  [ "${TARGET}" == "-" ] || \
  [ "${INPUT}" == "-" ] || \
  [ "${OUTPUT}" == "-" ] || \
  [ "${ARCH}" == "-" ]
then
  cat >&2 <<EOF
Usage:
  debian-package-builder [options]

  Arguments:

    -t, --target <target>: (required) target of build (nodejs)
    -i, --input <path>: (required) directory of input image spec
    -o, --output <path>: (required) directory to output build results
    -a, --arch <arch>: (required) architecture
    -n, --name <name>: optional name of image

  Flags:

    -h, --help: show this usage
    -d, --docker: build image using docker

  Docker-only arguments:

    --no-cache: optional flag to not do caching
    --debian-release <release>: optional Debian release (default: buster) 
    --target-version <version>: optional target version
      - default Node.js version: 10

  Examples:

    debian-package-builder --docker --target nodejs --input ./examples/hello-world --output ./output --arch amd64
EOF
  exit 1
fi

if [ "${NAME}" == "-" ]
then
  NAME="$(basename "${INPUT}")"
fi

if [ "${DOCKER}" = "y" ]
then
  ${DIRNAME}/build-docker ${ARGUMENTS}
else
  umask 022

  WORKDIR=$(mktemp -d)

  cp -r "${CWD}/${INPUT}" "${WORKDIR}/${NAME}"

  cd "${WORKDIR}/${NAME}"

  if [ -x "${WORKDIR}/${NAME}/source" ]
  then
    "${WORKDIR}/${NAME}/source"
    rm "${WORKDIR}/${NAME}/source"
  fi

  DEBUILD_ARGS=

  if [ "${TARGET}" == "nodejs" ]
  then
    DEBUILD_ARGS="${DEBUILD_ARGS} --preserve-envvar=NODE_TLS_REJECT_UNAUTHORIZED"
  fi

  apt-get update -y
  mk-build-deps \
    --install \
    --tool='apt-get -o Debug::pkgProblemResolver=yes --no-install-recommends --yes' \
    ${WORKDIR}/${NAME}/debian/control

  debuild \
    ${DEBUILD_ARGS} \
    -a${ARCH} \
    -uc \
    -us

  pwd
  ls -lh "${WORKDIR}"
  mkdir -p "${CWD}/${OUTPUT}/${NAME}"
  find "${WORKDIR}" -type f -name "${NAME}_*" | xargs cp -t "${CWD}/${OUTPUT}/${NAME}"

  cd "${CWD}"
fi
