#!/usr/bin/env bash

clear

WHICHENV=${1:-test}

NOW=$(date +%Y-%m-%d_%H:%M:%s)

declare -A ENVIRONMENTS
ENVIRONMENTS=([test]="dad-test.zooxlabs.com"
              [prod]="dad.zooxlabs.com"
              )

if [[ ${ENVIRONMENTS[$WHICHENV]} == "" ]]; then
        echo "Invalid enviroment: $WHICHENV -- select one of: ${!ENVIRONMENTS[@]}"
        exit 1
fi

declare -A JOBS
JOBS=([10]="update_merge_batch"
      [20]="merge_batch_from_s3"
      [30]="github_mergeable_retry"
      [40]="pull_requests_from_github"
      [50]="pull_requests_from_github"
      )

declare -A PARAMS
PARAMS=([10]="\'--update-log-tests\': None"
        [20]=""
        [30]=""
        [40]="\'--scope\': \'full\', \'--state\': \'all\'"
        [50]="\'--scope\': \'incremental\', \'--state\': \'open\'"
        )

declare -A MINUTES
MINUTES=([10]="13"
        [20]="11"
        [30]="3"
        [40]="60"
        [50]="2"
        )

for scrnm in ${!PARAMS[@]}
do
        /usr/bin/env python <<-!
import json
import requests

url = u"http://dkron.zooxlabs.com/v1/jobs"

job_cmd = '/usr/bin/env python -c \"import json; import requests; url = \'http://${ENVIRONMENTS[$WHICHENV]}/api/crontrigger/${JOBS[${scrnm}]}\'; payload = {${PARAMS[${scrnm}]}}; resp = requests.get(url=url,params=payload); print(url); print(payload); print(resp); print(resp.text);\"'
print "Processing job {} with job_cmd='{}'".format('$scrnm',job_cmd)
payload = {"name": "${scrnm}-${WHICHENV}-${JOBS[${scrnm}]}",
           "schedule": "@every ${MINUTES[${scrnm}]}m",
           "owner": "Infra Team",
           "owner_email": "rfagen@zoox.com",
           "disabled": False,
           "retries": 0,
           "concurrency": "allow",
           "executor": "shell",
           "executor_config": {
                "command": job_cmd
           }
          }
print "Sending payload of: {}\n".format(json.dumps(payload))
r = requests.post(url=url, data=json.dumps(payload))
print "data results:{}\ntext:{}\nurl:{}\n".format(r, r.text, r.url)
!
done
