#!/usr/bin/env bash

function printerror {
  echo "========   ERROR   ========="
  echo $*
  echo "============================"
}

function usage {
  echo "Execute on pipedream a job to get a list of PRs merged since a prior release"
  echo "usage: $0 [--help][--no_users]"
  echo "where:  --help       displays this message"
  echo "        --run_local  run against the local git repository, not pipedream"
  echo "        --no_users   ignores the user list"
  echo "        --users      list of git user IDs, default:"
  echo "                       cli jgoldman paul ravi ruyu smertens vfeinstein wsheng "
  echo "        --product    the name of the product team, default 'teleops'"
  echo "        --branch     ending branch or SHA to evaluate up to, default 'master'"
  echo "        --tag        git tag to start evaluating from, default is"
  echo "                       the last committed of the form 'ZX.AI.*.base'"
  echo "        --dry_run    don't execute, just echo the pipedef"
  exit 1
}

RELPRODUCT=""
BRANCHEVAL=""
TAGEVAL=""
USERLIST=""
USERCOUNT=0
NOUSERS=0
RUNLOCAL=0
DRYRUN=0

while [[ $# -gt 0 ]]; do
  case $1 in
    --help)
      usage
      ;;
    --dry_run)
      DRYRUN=1
      shift
      ;;
    --run_local)
      RUNLOCAL=1
      shift
      ;;
	  --no_users)
			shift
			NOUSERS=1
			;;
    --users)
      shift
      ISUSER=$1
      while [[ "${ISUSER:0:2}" != "--" &&  $# -gt 0 ]]; do
        USERLIST+=" $ISUSER"
        let USERCOUNT+=1
        shift
        ISUSER=${1:-}
      done
      ;;
    --product)
      shift
      RELPRODUCT=$1
      shift
      ;;
    --branch)
      shift
      BRANCHEVAL=$1
      shift
      ;;
    --tag)
      shift
      TAGEVAL=$1
      shift
      ;;
    *)
      printerror "Unrecognized parameter(s): '$*'"
      usage
      ;;
  esac
done

#this is the software product you're generating release notes for
RELPRODUCT=${RELPRODUCT:-teleops}

#this is the branch you want to get PRs from
BRANCHEVAL=${BRANCHEVAL:-master}

#this is the release tag you want to be your "beginning of time"
TAGEVAL=${TAGEVAL:-$(git tag -l ZX.AI.*.base | tail -1)}

#this is the list of user IDs for which you want all their commits
USERLIST=${USERLIST:-cli jgoldman paul ravi ruyu smertens vfeinstein wsheng}

############################################
##  NO USER SERVICEABLE PARTS BELOW HERE  ##
##                                        ##
##   _\~  ELECTROCUTION HAZARD  ~/_       ##
############################################

# Unique-ifiers
EPOCHSECS=$(date +'%s')
FILEDIR='/nfs/pipedream/archives/release_notes'
REQUESTOR=$(whoami)
LOGFILE=$FILEDIR/${REQUESTOR}-${EPOCHSECS}.log
echo "## -*- coding: utf-8 -*-" > ${LOGFILE}
chmod 666 ${LOGFILE}

# git request related variable mashing
if [[ $NOUSERS -eq 1 ]]; then
  RESOLVED_USERS=" "
else
  RESOLVED_USERS="$(for USER in $USERLIST; do echo --author=$USER; done)"
fi
LOCAL_FORMATSTRING='--format="%h %an %s"'
PIPEDEF_FORMATSTRING='--format=\"%h %an %s\"'
GITCOMMAND="echo '<pre>' >> ${LOGFILE}; git fetch --tags --quiet origin ${BRANCHEVAL}; git checkout --quiet ${BRANCHEVAL}; git pull origin ${BRANCHEVAL}; git"
GITARGHEAD="log --first-parent $RESOLVED_USERS HEAD...$TAGEVAL"
GITARGHEAD=$(echo $GITARGHEAD)
GITARGTAIL="-- >> ${LOGFILE} 2>&1"

# for sending the results back
MAILCOMMAND="./scripts/setup/setup.sh dev --no-ask-pass --tags=bazel; echo '</pre>' >> ${LOGFILE}; echo {} | bazel run //base/mail:send_mail -- --template ${LOGFILE} --from ${REQUESTOR}@zoox.com --to ${REQUESTOR}@zoox.com --subject ${RELPRODUCT}:${BRANCHEVAL}:${LOGFILE}"

# curl-ifications
AUTHHEADER="Authorization:sudo user=${REQUESTOR}"
CONTENTHEADER="Content-Type: application/json"
SCHED_URL="http://pipedream-scheduling.zooxlabs.com/v1/pipeline"

# the pipeline definition
PIPEDEF=$(cat <<-!
{
    "pipedef": {
        "job": [
            {
                "taskCount": 1,
                "arg": [
                    "$GITARGHEAD $PIPEDEF_FORMATSTRING $GITARGTAIL"
                ],
                "command": "${GITCOMMAND}",
                "alertEmail": [
                    "${REQUESTOR}@zoox.com"
                ],
                "branch": "${BRANCHEVAL}",
                "skipDrivingSetup": true,
                "slackAlertTarget": [
                    "@${REQUESTOR}"
                ],
                "name": "get_commits"
            },
            {
                "taskCount": 1,
                "command": "${MAILCOMMAND}",
                "alertEmail": [
                    "${REQUESTOR}@zoox.com"
                ],
                "branch": "${BRANCHEVAL}",
                "skipDrivingSetup": true,
                "slackAlertTarget": [
                    "@${REQUESTOR}"
                ],
                "dependency": [
                    {
                        "dependencyType": "AFTER_ANY",
                        "jobName": "get_commits"
                    }
                ],
                "name": "send_email"
            }
        ],
        "name": "${RELPRODUCT}_release_notes"
    }
}
!
)

# where the magic happens!!!
LOCAL_COMMAND="${GITCOMMAND} ${GITARGHEAD} '$LOCAL_FORMATSTRING' ${GITARGTAIL}"
echo $PIPEDEF > ${EPOCHSECS}.sent.json
if [[ $DRYRUN -eq 1 ]]; then
  echo Not executing report.
  if [[ $RUNLOCAL -eq 1 ]]; then
    echo local command:
    echo $LOCAL_COMMAND
  else
    echo pipedef:
    cat ${EPOCHSECS}.sent.json
  fi
  exit
fi
if [[ $RUNLOCAL -eq 0 ]]; then
  curl -v -o ${EPOCHSECS}.curl.log -H "${AUTHHEADER}" -H "${CONTENTHEADER}" --data "@${EPOCHSECS}.sent.json" ${SCHED_URL} > ${EPOCHSECS}.curl.stdout 2> ${EPOCHSECS}.curl.stderr
  if [[ $? -eq 0 ]]; then
    echo Success
    echo =======
    cat ${EPOCHSECS}.curl.log
  else
    echo Some Kind of Problem
    echo ====================
    less ${EPOCHSECS}*
  fi
  exit
fi
echo Running locally:
eval "$LOCAL_COMMAND"
echo results in $LOGFILE
