#!/bin/bash

if [[ -e "./aws.config" ]]; then
    export AWS_CONFIG_FILE="./aws.config"
else
    export AWS_CONFIG_FILE="$HOME/.aws/config"
fi

SOURCE_DIR="./dist/"
SITE="crafting-guide.com"
TARGET=""
while [[ "$1" != "" ]]; do
    case "$1" in
        "--staging") TARGET="staging";;
        "--production") TARGET="production";;
    esac
    shift
done

if [[ "$TARGET" == "" ]]; then
    echo "Please choose either --staging or --production for the target."
    exit 1
fi

if [[ "$TARGET" == "staging" ]]; then
    TARGET_DIR="s3://new.$SITE/"
elif [[ "$TARGET" == "production" ]]; then
    TARGET_DIR="s3://$SITE/"
fi

S3CMD_CFG="$HOME/.s3cfg"
if [[ ! -e "$S3CMD_CFG" ]]; then
    echo "[default]" > "$S3CMD_CFG"
    cat $AWS_CONFIG_FILE | grep "aws_access_key_id" | sed "s/aws_access_key_id/access_key/" >> "$S3CMD_CFG"
    cat $AWS_CONFIG_FILE | grep "aws_secret_access_key" | sed "s/aws_secret_access_key/secret_key/" >> "$S3CMD_CFG"
fi

if grunt clean dist; then
    echo "Preparing to upload to S3..."
    s3cmd sync -r --add-header="cache-control:max-age=1800" $SOURCE_DIR $TARGET_DIR
    echo "S3 Upload Complete"
else
    echo "ERROR: Building distribution failed. Aborting deployment!"
    exit 1
fi
