#!/usr/bin/env bash
#-*- mode: sh; -*-

set -x

scan="@SCANDEPS@ -r --no-core"

# script to create a CPAN distribution of a Botocore API

BOTOCORE_PATH=${BOTOCORE_PATH:-$(pwd)/src/main/perl/lib/botocore}

if ! test -d $BOTOCORE_PATH/botocore; then
    >&2 echo "BOTOCORE_PATH invalid"
    exit 1;
fi

if test -z "$1"; then
    >&2 echo "usage: create-service service"
    exit 1
fi

module_name="$2";

if test -n "$module_name"; then
    MODULE="-m $module_name"
fi

>&2 echo "using BOTOCORE_PATH=$BOTOCORE_PATH"

trap 'test -n "$tmpdir" && rm -rf $tmpdir' EXIT

tmpdir=$(mktemp -d)

>&2 echo "creating stub for service : $1"

if ! amazon-api -s $1 $MODULE -o $tmpdir create-stub; then
    echo "exit code: $?"
fi

pushd $tmpdir >/dev/null

if test -z "$module_name"; then
    module_name=$(basename $(find  Amazon/API -type d | grep -v 'API$'))
fi

nmethods=$(ls -1 Amazon/API/$module_name/ | wc -l)
>&2 echo "...$nmethods methods are implemented by Amazon::API::$module_name"
PERL_MODULE="Amazon::API::$module_name";

>&2 echo "creating shapes for $PERL_MODULE"
amazon-api -s $1 $MODULE -o $tmpdir create-shapes
nshapes=$(ls -1 Amazon/API/Botocore/Shape/$module_name/* | wc -l)

>&2 echo "...$nshapes shapes created for $PERL_MODULE"
scan="scandeps-static.pl -r --no-core"

>&2 echo "scanning for dependencies..."
requires=$(mktemp)

$scan Amazon/API/$module_name.pm >$requires
$scan $(ls -1 Amazon/API/$module_name/*.pm | head -1) >>$requires
$scan $(ls -1 Amazon/API/Botocore/Shape/$module_name/*.pm | head -1) >>$requires

sort -u $requires > requires

>&2 echo "creating package perl-Amazon-API-$module_name.tar.gz"

description=$(amazon-api -s $module_name help | perl -0 -ne 'print $1 if /DESCRIPTION\n\s*([^\n]+)\n/;')

mkdir lib
mv Amazon lib/
mkdir bin/

PROJECT_HOME=$tmpdir make-cpan-dist \
	   -e bin \
	   -l lib \
	   -c \
	   -M 5.016 \
	   -m $PERL_MODULE \
	   -a 'Rob Lauer' \
	   -d "$description" \
	   -H $(pwd) \
	   -D requires 1>&2

popd >/dev/null

cp $tmpdir/*.tar.gz .

# rm -rf $tmpdir/

