#!/usr/bin/env bash
set -e
#set -x

# see jenkinsfile for version to build
NC_VERSION=${NC_VERSION:-18}
LOCAL_IMAGE=xaicorp/nextcloud
TAG=${NC_VERSION}.0-${BUILD_NUMBER:-dev}
REMOTE_IMAGE=dkregistry.xai-corp.net:5000/${LOCAL_IMAGE}:${TAG}

LOG=$(mktemp)

export LOCAL_IMAGE
export REMOTE_IMAGE
export TAG

dc() {
#    export NC_VERSION=${NC_VERSION}
    # shellcheck disable=SC2068
    docker-compose \
    -f docker-compose.yml \
    -f docker-compose.build.yml \
    $@
}

####
build() {
  echo -e "\e[33m building the image\e[39m"
  dc build
}

build_test() {
  echo -e "\e[33m testing the image\e[39m"

  dc run --rm app php /usr/src/nextcloud/occ --version | grep ${NC_VERSION}


  #test for smbclient installed
  dc run --rm --user www-data app which smbclient
}



build_save() {
  echo -e "\e[33m saving the image\e[39m"

  docker tag "$LOCAL_IMAGE:$TAG" "$REMOTE_IMAGE"
  docker push "$REMOTE_IMAGE"
}

function trap_exit() {
  code=$?
  dc down
  if [ $code -gt 0 ]; then
    echo
    cat "$LOG"
    rm "$LOG"
    dc logs --tail=10
    echo -e "\033[31mFailed to build functional image\033[39m"
    exit $code
  fi

  rm "$LOG"
  echo -e "\033[32mSuccess:\033[39m ${LOCAL_IMAGE}:${TAG} successfully built"
}
trap  trap_exit EXIT

print_usage() {
  printf "Usage: %s: [-b] [-t] [-s] \n" "$0"
  echo -b build
  echo -t test
  echo -s push to registry
  echo -h help
  exit 0
}

######
if [ -z "$1" ]; then
  build && build_test && build_save
  exit
fi

while getopts btdhs name
do
    case $name in
    b)    build;;
    t)    build_test;;
    s)    build_save;;
    *)    print_usage;;
    esac
done
