#!/usr/bin/env bash

set -e

# build-package-from-git - Job handler for Marang
# Author: Willam Petit <wpetit@cadoles.com>
#
# Dependencies:
#
#   - jq - https://stedolan.github.io/jq/ - apt-get install jq
#   - git
#
# Arguments:
#
#   - $1: Docker distribution to use for building package - Default: debian:jessie
#   - $2: Limit the build for commits in this specified branch - Default: No branch limitation

#---------Config---------

TAMARIN_PATH=$(readlink -f ../../tamarin)
#------------------------

#---------Functions---------

function get_payload_opt {
  echo "$MARANG_PAYLOAD" | jq -r "$1"
}

function clean_workspace {
  # Clean workspace
  echo "Cleaning workspace $workdir..."
  rm -rf "$workdir"
}

#---------------------------

# Get handlers arguments
DISTRIB=$1
LIMIT_TO_BRANCH=$2
OUTPUT_DIR=$3

# Create temporary workspace
workdir=$(mktemp -d)
cd "$workdir"
trap clean_workspace EXIT

echo "Using workspace $workdir..."

# Create temporary dist directory
mkdir -p "$workdir/dist"

# Extract project info
project_name=$(get_payload_opt ".repository.name" | tr '[:upper:]' '[:lower:]')
repo_url=$(get_payload_opt ".repository.clone_url")
commit=$(get_payload_opt ".ref")

# Fetch project sources
GIT_SSL_NO_VERIFY=true git clone "$repo_url" "$project_name"
cd "$project_name"

# Limit the build to a specific branch if needed
if [ ! -z "$LIMIT_TO_BRANCH" ]; then

  echo "The build processus is limited to $LIMIT_TO_BRANCH..."

  git checkout "$LIMIT_TO_BRANCH"

  branches_containing_commit=$(git branch --contains $commit)

  if [[ ! "${branches_containing_commit[@]}" =~ "$LIMIT_TO_BRANCH" ]]; then
    echo "The commit $commit is not part of $LIMIT_TO_BRANCH !"
    clean_workspace
    exit
  fi

fi

# Checkout specified commit
git checkout "$commit"
git submodule init
git submodule update

echo "Building package..."

# Build on package per version
set +e
COMMIT_TAGS=$(git describe --exact-match --abbrev=0) #git tag -l --contains HEAD | grep "^pkg")
set -e
if [[ -z ${COMMIT_TAGS} ]]
then
   echo "Nothing to build :"
   echo "   - No build build tags on last commit"
   clean_workspace
   exit
fi

for tag in ${COMMIT_TAGS}
do
   PACKAGE_ENV=$(echo ${tag} | cut -d '/' -f 2)
   PACKAGE_DISTRIB=$(echo ${tag} | cut -d '/' -f 3)
   PKGVERSION=$(echo ${tag} | cut -d '/' -f 4)

   # Setting package version
   [[ -z ${PKGVERSION} ]] && PKGVERSION="NO-VERSION"

   cd ${workdir}/${project_name}
   tamarinrc="${workdir}/${project_name}/.tamarinrc"
   [[ ! -f ${tamarinrc} ]] && touch ${tamarinrc}
   set +e
   grep -q "^project_version=.*" ${tamarinrc}
   if [[ ${?} -eq 0 ]]
   then
      sed -i -e "s/^project_version=.*/project_version=${PKGVERSION}/" ${workdir}/${project_name}/.tamarinrc
   else
      echo "project_version=${PKGVERSION}" > ${tamarinrc}
   fi
   
   if [[ ${PACKAGE_ENV} =~ ^(staging|stable) ]]
   then
      grep -q "^no_version_suffix=.*" ${tamarinrc}
      if [[ ${?} -eq 0 ]]
      then
         sed -i -e "s/no_version_suffix=.*/no_version_suffix=yes/" ${tamarinrc}
      else
      	 echo "no_version_suffix=yes" >> ${tamarinrc}
      fi
   fi
   set -e

   # Build package with Tamarin for specified distrib
   echo
   echo "Building package with $TAMARIN_PATH/package (${tag})"
   echo
   "$TAMARIN_PATH/package" "$workdir/$project_name" -o "$workdir/dist" -b "$DISTRIB"

  # Copy debian packages to destination directory if arguments is specified
   if [ ! -z $OUTPUT_DIR ]; then
      DEST_DIR="$OUTPUT_DIR/$LIMIT_TO_BRANCH/$project_name"
      mkdir -p "$DEST_DIR"
      echo "Copying packages to $DEST_DIR/..."
      cp $workdir/dist/*.deb "$DEST_DIR/"
   else
     echo "No output directory specified."
   fi

   # Deploy packages automatically based on tags
  
   # Check that the package environment matches the expected ones
   if [[ "$PACKAGE_ENV" =~ ^(dev|staging|stable)$ ]]; then
      echo
      echo "Pushing packages to matching '$PACKAGE_ENV' repository ..."
      echo
      ssh aptly@vulcain.cadoles.com mkdir -p "/home/aptly/packages/$PACKAGE_ENV/$LIMIT_TO_BRANCH"
      scp -r $workdir/dist/*.deb "aptly@vulcain.cadoles.com:/home/aptly/packages/$PACKAGE_ENV/$LIMIT_TO_BRANCH/"
      echo "Cleaning builded package"
      rm -rf $workdir/dist/*
   else
      echo "Packaging tag prefix 'pkg' found but the environment token does not match any of 'dev', 'staging' or 'stable'. Ignoring..."
   fi
done