WORKSPACE=${WORKSPACE:-$( cd $(dirname $0)/../../.. ; pwd -P )}

$RUN_SIGNSTEP

function getBranchName ()
{
  local branchName
  branchName=`git symbolic-ref HEAD 2>/dev/null || echo detached`

  if [ "$branchName" != "detached" ] # if we are not detached
  then
    #we are attached - use the branchname then
    if echo $branchName | grep pr 2>&1 > /dev/null
    then
      #if this is a pull request branch - fetch the pr number and prefix with "PR"
      #refs/heads/number/head
      echo PR$(echo $branchName | awk '{gsub(".*/pr/","");print $1}' | awk '{gsub("/.*","");print $1}')
    else
      #if we are on a normal branch - fetch branchname
      #refs/heads/branchname
      echo $branchName | awk '{gsub(".*/","");print $1}'
    fi
  else
    #if we are in detached head state
    #fetch the first non-pullrequest branch we can find with HEAD
    #also only grep in remotes that match current GITHUB_REPO
    git branch -r --contains HEAD | sed "/origin\/pr\//d" | grep $GITHUB_REPO | head -n1 | awk '{gsub(".*/","");print $1}'
  fi
}


function getBuildRevDateStr ()
{
  local revStr
  #fetch date-rev
  revStr=`git --no-pager log --abbrev=7 -n 1 --pretty=format:"%h %ci" HEAD | awk '{gsub("-", "");print $2"-"$1}' 2>/dev/null`
  if [ "$?" == "0" ]
  then
    #fetch the first branch containing head
    revStr=$revStr"-"$(getBranchName)
    if [ "$?" == "0" ]
    then
      echo $revStr
    else
      echo "Unknown"
    fi
  else
    echo "Unknown"
  fi
}

#rename for upload
#e.x. kore-20130314-8c2fb31.apk.
UPLOAD_FILENAME="kore-$(getBuildRevDateStr).apk"
cd $WORKSPACE;mv app/build/outputs/apk/release/*.apk $UPLOAD_FILENAME
