#!/bin/bash
#
# generate_patches - create patched files using diffs and the original 
# files. Takes 3 parameters: --confdir --outputdir --sourcedir
#
# Copyright (c) 2018 Electric Cloud, Inc.
# All rights reserved
#

SCRIPTPATH="$(cd "${0%/*}" && echo $PWD)"
source $SCRIPTPATH/patch_utils.sh
EAPATCH_LOGGING=1

# create patches in the specified output path for this configuration.
TEMP=$(getopt  -n 'generate_patches' --longoptions "confdir:,outputdir:,sourcedir:" '' "$@")

if [ $? != 0 ] ; then 
    eapatch_error "could not parse options to generate_patches. Terminating." 
    exit $ERR_BADARG
fi

# Note the quotes around `$TEMP': they are essential!
eval set -- "$TEMP"

CONFDIR=
OUTPUTDIR=
SOURCEDIR=

while true; do
  case "$1" in
    --confdir )     # Where the diffs will be discovered 
        CONFDIR="$2"
        shift 2
        ;;
    --outputdir )  # where to create the patches
        OUTPUTDIR="$2" 
        shift 2
        ;;
    --sourcedir )  # root of where the source files are
        SOURCEDIR="$2" 
        shift 2
        ;;
    * ) break ;;
  esac
done



if [ ! -d "$SOURCEDIR" ]; then
    eapatch_error "--sourcedir option is missing or not a directory"
    exit $ERR_BADARG 
else
    # make it absolute because the patch utility seems to not handle
    # paths like ../AndroidO/ 
    SOURCEDIR=$(cd "$SOURCEDIR" && echo $PWD) 
fi
if [ ! -d "$CONFDIR" ]; then
    eapatch_error "--confdir option is missing or not a directory" 
    exit $ERR_BADARG 
fi

if [ ! -d "$OUTPUTDIR" ]; then
    eapatch_error "--outputdir option is missing or not a directory" 
    exit $ERR_BADARG
fi


missing_tools="$(eapatch_checktools )"
if [ $? -ne 0 ]; then
    eapatch_error "Some required tools not found: $missing_tools"
    exit $ERR_NOTOOL
fi

eapatch_generate_patches $CONFDIR $SOURCEDIR $OUTPUTDIR

