#!/bin/bash
# Copyright ETSI 2017
# See: https://forge.etsi.org/etsi-forge-copyright-statement.txt

# Merges OpenAPIs interfaces in the working directory
# and validates them individually.
# Exit status is 0 if all validation passed, 1 otherwise

# Usage:
# $0 <working-directory> <storage-dir>

#set -x

function store_api () {
	f="$1"
	cp -v "$1" "${storage_dir}/"
}

function validate_api () {
  file="$1"
  api="$2"
  deliverable="$3"
  echo "--- Merging file."
  merged_file="${deliverable}-${api}-API.yaml"
  json-refs resolve "${file}" > "${merged_file}"

  echo "--- Validating ${merged_file}"
  swagger-tools validate "${merged_file}"
  vres=$?
  echo "--- Validation done ($res)."

  # If validation succedes, store the generated file
  [ $vres ] && store_api "${merged_file}"
  
  return $vres
}


## Main ##

wd="${1?"Usage: $0 <working-directory> <storage-directory>"}"
storage_dir="${2?"Usage: $0 <working-directory> <storage-directory>"}"

echo "Entering dir $wd"
cd "$wd"

# Stores the overall validation result
# (single results in OR)
fres=0

for d in */ ; do

    if [ -z "$d" -o "$d" = "*/" ]; then
        continue
    fi
 
    deliverable="${d::-1}"
    echo "#### Checking directory $deliverable ($d)"
    
    cd "$deliverable"
    for dd in */ ; do

        if [ -z "$dd" -o "$dd" = "*/" ]; then
            continue
        fi
        
        api="${dd::-1}"
        echo "########## Checking directory $api ($dd)"
        cd "$dd"
        for file in ./*; do
            file_name="${file:2}"
            #echo "-- $file"
            #echo "-- Checking file $file_name"

            if [ "$file_name" == "$api.yaml" ]; then            
	              validate_api "$file_name" "$api" "$deliverable"
	              res=$?
                fres=$(($fres||$res))
            fi
        done
        echo 
        cd ..
     done
     cd ..
done

# Exit code needed for jenkins to know the verdict of the build
echo "-- Final validator returns $fres."
exit $fres

