#!/bin/bash

set -e

## Colour for bash prompt
RED="\033[01;31m"
GREEN="\033[01;32m"
RESET="\033[00m"

cleanup () {
    rm -rf "${TEMP_DIR}"
}

trap cleanup EXIT

display_help () {
    printf "Usage: dufflebag AWS_REGION\n"
    printf "Example: dufflebag us-east-1\n"
    printf "Dufflebag can only operate in one AWS region at a time\n"
    printf "If you want to search every region, you'll have to deploy several instances.\n"
    printf "See also /usr/share/doc/dufflebag/README.md\n"
}

if [ -z "$1" ] || [ "$1" == "--help" ] || [ "$1" == "-h" ]; then
    display_help
    exit 0
fi

##Check if this is a correct aws code
if ( echo $1 | grep -qE  "^[a-z]{2}-[a-z]*-[0-9]$" ); then
    printf "\n${GREEN}[>]${RESET} The aws region is '$1'\n"
else
    printf "\n${RED}[-]${RESET} ERROR: '$1' does not seem to be a correct aws region\n"
    display_help
    exit 1
fi

TEMP_DIR=$(mktemp -d)
if [ ! "$TEMP_DIR" ] || [ ! -d "$TEMP_DIR" ]; then
    printf "\n${RED}[-]${RESET} ERROR: error while creating the temporary directory\n"
    exit 1
fi

# keep current dir
current_dir=$(pwd)

cp -r /usr/share/dufflebag/* "$TEMP_DIR"
cp -r /usr/share/dufflebag/.ebextensions "$TEMP_DIR"
sed -i "s/^var aws_region =.*/var aws_region = \"$1\"/" "$TEMP_DIR"/region.go

printf "\n${GREEN}[>]${RESET} Generate dufflebag.zip"
cd "$TEMP_DIR" && export GOPATH=/usr/share/gocode && make

cd $current_dir

printf "\n${GREEN}[>]${RESET} Copy dufflebag.zip in current directory"
cp "$TEMP_DIR"/dufflebag.zip ./

printf "\n${GREEN}[>]${RESET} The dufflebag.zip is available in current directory"
printf "\n${GREEN}[>]${RESET} See /usr/share/doc/dufflebag/README.md for
an explanation of how to use the generated file dufflebag.zip\n"
