#!/bin/sh

usage() {
    cat <<EOF
usage: ${0##*/} [command]
    -h          Print this help message.
    -v          Validate terraform config.
    -p          Show changes required by the current terraform config.
    -a          Create or update infraestructure.
    -d          Destroy infraestructure.
    -l		Create zip files of the lambdas.
EOF
    exit 1
}

RUN=
while getopts "hvpadl" OPTION; do
    case $OPTION in
    a) RUN=apply ;;
    v) RUN=validate ;;
    p) RUN=plan ;;
    d) RUN=destroy ;;
    l) RUN=lambda ;;
    *) usage ;;
    esac
done

dir="$PWD"

if [ "$RUN" = 'lambda' ]; then
    cd "$dir/terraform/resources/lambda" || exit
    lambdas=$(find -H . -maxdepth 1 -mindepth 1 -type d -printf "%f\n")
    for lambda in $lambdas; do
	cd $lambda || exit
	zip $lambda.zip lambda_handler.py
	mv $lambda.zip ..
	cd ..
    done
    exit
fi

cd "$dir/terraform/organization" || exit

terraform init
if [ "$RUN" = 'apply' ]; then
    terraform plan
    terraform apply --auto-approve
else
    terraform "$RUN"
fi