#!/bin/bash

source `dirname $0`/../../../etc/release/_common.sh
set -e

function usage() {
    colour_echo red "Error: $*"
    colour_echo cyan "Usage: `basename $0` --committer.name NAME --committer.email EMAIL --baseline.repo REPO_NAME --baseline.repo.url REPO_URL --branch.name BRANCH_NAME [--sandbox.directory SANDBOX_DIR] --stash.base.url STASH_URL --stash.user.credentials FILE --stash.project KEY"
    colour_echo cyan "  --committer.name NAME: The name of the committer that will check in the newly generated screenshots into the sandbox"
    colour_echo cyan "  --committer.email EMAIL: The email address of the committer that will check in the newly generated screenshots into the sandbox"
    colour_echo cyan "  --baseline.repo REPO_NAME: The baseline images repository name"
    colour_echo cyan "  --baseline.repo.url REPO_URL: The baseline images repository clone URL"
    colour_echo cyan "  --branch.name BRANCH_NAME: The baseline images repo branch to check out"
    colour_echo cyan "  --sandbox.directory SANDBOX_DIR: The sandbox directory name"
    colour_echo cyan "  --stash.base.url STASH_URL: The base URL of your Stash Instance."
    colour_echo cyan "  --stash.user.credentials FILE: The file containing your Stash user credentials for creating a pull request"
    colour_echo cyan "  --stash.project KEY: The Stash project key for the baseline images repo"
    exit 99
}

COMMITTER_NAME=
COMMITTER_EMAIL=
BASELINEREPO=
BASELINEREPO_URL=
BRANCHNAME=
SANDBOXDIR=
STASHURL=
STASH_USER_CREDENTIALS=
STASHPROJECTKEY=

while [ $# -gt 0 ]
do
    case $1 in
    --committer.name )
        COMMITTER_NAME=$2
        if [ "$COMMITTER_NAME" = "" ]
        then
            usage The name of the committer that will check in the newly generated screenshots into the sandbox
        fi
        shift
        ;;
    --committer.email )
        COMMITTER_EMAIL=$2
        if [ "$COMMITTER_EMAIL" = "" ]
        then
            usage The email address of the committer that will check in the newly generated screenshots into the sandbox
        fi
        shift
        ;;
    --baseline.repo )
        BASELINEREPO=$2
        if [ "$BASELINEREPO" = "" ]
        then
            usage The baseline images repository name is required
        fi
        shift
        ;;
    --baseline.repo.url )
        BASELINEREPO_URL=$2
        if [ "$BASELINEREPO_URL" = "" ]
        then
            usage The branch name for your baseline images is required
        fi
        shift
        ;;
    --branch.name )
         BRANCHNAME=$2
         if [ "$BRANCHNAME" = "" ]
         then
             usage The baseline images repository clone URL is required
         fi
         shift
         ;;
    --sandbox.directory )
        SANDBOXDIR=$2
        if [ "$SANDBOXDIR" = "" ]
        then
            usage The baseline images sandbox directory name is required
        fi
        shift
        ;;
    --stash.base.url )
        STASHURL=$2
        if [ "$STASHURL" = "" ]
        then
            usage The URL to your Stash instance is required
        fi
        shift
        ;;
    --stash.user.credentials )
        STASH_USER_CREDENTIALS=$2
        if [ "$STASH_USER_CREDENTIALS" = "" ]
        then
            usage The path to the file containing the Stash user login credentials is required
        fi
        shift
        ;;
    --stash.project )
        STASHPROJECTKEY=$2
        if [ "$STASHPROJECTKEY" = "" ]
        then
            usage The baseline images repository project key in Stash is required
        fi
        shift
        ;;
    * )
        usage
        ;;
    esac
    shift
done

cd $BASELINEREPO

export COMMITID=`git rev-parse HEAD`
export CHANGECOUNT=`find ../stash/func-test/visual-regression-test/target -name "*.png" | grep -P '.*report_images/(?!old|boxold|boxnew|boxdiff|diff).*' | wc -l`

if (($CHANGECOUNT == 0))
then
    banner "No screenshots changed. Nothing more to do!"
    exit 0
else
    banner "Exporting screenshots to sandbox"
fi

echo "It seems $CHANGECOUNT screenshots changed. Time to push some screenshots around."
echo "Let $COMMITID go down in the annals of our screenshot history! "

if [ "`git remote show`" == "origin" ]
then
    git remote set-url origin $BASELINEREPO_URL
else
    git remote add origin $BASELINEREPO_URL
fi
git fetch -q origin
git config --local user.name "$COMMITTER_NAME"

if [ "$BUILDUSER" != "" ]
then
    git config --local user.email "$BUILDUSER@atlassian.com"
else
    git config --local user.email "$COMMITTER_EMAIL"
fi

cd ..
export STASHUSER=`grep stash.user $STASH_USER_CREDENTIALS| cut -d'=' -f2`
export STASHPASS=`grep stash.password $STASH_USER_CREDENTIALS| cut -d'=' -f2`

cp -R $BASELINEREPO $SANDBOXDIR
find stash/func-test/visual-regression-test/target -name "*.png" | grep -P '.*report_images/(?!old|boxold|boxnew|boxdiff|diff).*' | xargs cp -t $SANDBOXDIR

cd $SANDBOXDIR

cat <<EOF > commitmsg.txt

New screenshots added to sandbox from $BUILDKEY

Based off commit $COMMITID
Build URL: $BUILDURL

EOF

git checkout -q -b sandbox/$BUILDKEY
git add *.png
git commit --file=commitmsg.txt
git push origin sandbox/$BUILDKEY

banner "Hooray, new screenshots have been pushed into a new branch :)"
rm commitmsg.txt

banner "Creating Pull Request in Stash at $STASHURL"

export PULLREQUESTRESTURL=$STASHURL/rest/api/latest/projects/$STASHPROJECTKEY/repos/$BASELINEREPO/pull-requests
curl \
    -i \
    -H "Accept: application/json" \
    -H "Content-Type: application/json" \
    -u $STASHUSER:$STASHPASS \
    -X POST \
    -s -S \
    -d@- \
    "$PULLREQUESTRESTURL" <<EOF
{
    "title": "New screenshots generated from $BUILDKEY",
    "description": "These screenshots have changed from the baseline. Please review them before merging this pull request to update them.
                    \n\nThe corresponding Visual Regression Test Reports are at $BUILDURL/artifact",
    "fromRef": {
        "id": "refs/heads/sandbox/$BUILDKEY",
        "repository": {
            "slug": "$BASELINEREPO",
            "project": {
                "key": "$STASHPROJECTKEY"
            }
        }
    },
    "toRef": {
        "id": "refs/heads/$BRANCHNAME",
        "repository": {
            "slug": "$BASELINEREPO",
            "project": {
                "key": "$STASHPROJECTKEY"
            }
        }
    }
}
EOF

echo
banner "Successfully created a pull request in Stash for sandbox/$BUILDKEY!"