apiVersion: v1
data:
  bitbucket.sh: "#!/bin/bash\n\n#this script funtions only work for bitbucket central
    repository\n\n#this script funtions only work for git repo\n#env variables needed
    for this to work are as below\n#***git_url=\"example.bitbucket.com\" make sure
    you dont add http/https or / in the url\n#****git_repo=\"pipelinepromotion\" repo
    to be pushed/download pipeline json files from\n#***git_project=\"kes\" project
    key is needed to clone/push/pull merge code\n#***git_user=\"tes.user\" user is
    needed for cloning and pusing changes (stash does not support only access key)\n#***git_branch=\"testbranch\"
    the branch to which the code should be merged with\n#***merge_branch=false if
    true then provide all the below env variables\n#   git_secret_token=\"dafjaljoahfoasjoijso\"
    needed to create pull requests should be the git_users secret token\n#   git_pr_token=\"slkdfjaljoajfopaj\"
    this is approver token to approve pull requests / you can also provide approver
    password here.\n#   git_approve_user=\"test.approver\"  username of the pull request
    approver\n#   git_password=\"adjoowddaw\" make sure your password does not include
    special characters like # @*/. special characters cause git clone command to fail
    with https\n#\n#  repo_type=\"stash\" for selfhosted bitbucket server please use
    stash as repo type\n#***root_folder=\"path/to/pipeline-promotion/folder\" folder
    to be selected in the repo to which the pipeline jobs to be pushed\n#***command=upload
    for running specific job -\n#                                         upload -
    to upload spinnaker pipeline json files to repo\n#                                         download
    - to download pipeline json file from repo and apply on spinnaker\n#***spinnaker_applications=\"testapp,sampleapp\"
    application needed to collect the pipeline information\n#spinnaker_pipelines=\"\"
    provide pipelines to be collected, if nothing given, all the pipelines of the
    application are collected\n#git_secret_sshkey=\"sshkey\" ssh key if you want to
    clone repo with ssh protocol\n\n# note *** env variables are mandatory to work
    with the script\n\nsource scripts/git.sh\ngit_bitbucket_api=$git_api_url\npr_id=0\napprove_pr_bitbucket(){\n
    \ approve_req=$(curl -X POST -u $git_approve_user:$git_pr_token \\\n  $git_bitbucket_api${git_project}/${git_repo}/pullrequests/${pr_id}/approve
    -o -I -L -s -w \"%{http_code}\")\n  echo $approve_req\n  if [[ $approve_req ==
    \"200\" ]];then\n    echo \"merge request approved successfully\"\n  else\n    echo
    \"FAIL: failed to approve the request \"\n    exit 1\n  fi\n}\n\nmerge_pr_bitbucket(){\n\n
    \ merge_req=$(curl  -X POST -u $git_user:$git_secret_token   \\\n  $git_bitbucket_api${git_project}/${git_repo}/pullrequests/${pr_id}/merge
    -o -I -L -s -w \"%{http_code}\")\n  echo $merge_req\n  if [[ $merge_req == 200
    \ ]]; then\n    echo \"merged pr successfully\"\n  elif [[ $merge_req == 202 ]];
    then\n    echo \"merging is in progress will be merged in less than a min\"\n
    \ else\n    echo \"FAILED: failed to merge $merge_pr\"\n    exit 1\nfi\n}\ncreate_pr_bitbucket(){\n\n\tlocal
    output=$(curl  -X POST -H \"Content-Type: application/json\" -u $git_user:$git_secret_token
    \  $git_bitbucket_api${git_project}/${git_repo}/pullrequests -d '{\n    \"title\":
    \"merging '$git_branch' to '$target_branch'\",\n    \"source\": {\n            \"branch\":
    {\n                \"name\": \"'$git_branch'\"\n            }\n        },\n        \"destination\":
    {\n            \"branch\": {\n                \"name\": \"'$target_branch'\"\n
    \           }\n        }\n}')\n  echo $output\n  echo $output > pr_response.json\n
    \ grep  \"There are no changes to be pulled\" pr_response.json\n  if [ \"$?\"
    = 0 ]\n  then\n    echo \"master branch is already up-to-date\"\n    exit 0\n
    \ else\n    pr_id=$(cat  pr_response.json| jq '(.id)' | sed 's/\\\"//g')\n    if
    [ $? = 0 ]; then\n      echo \"successfully created pull request \"\n      #rm
    -f pr_response.json\n    else\n      echo \"ERROR: failed to raise pull request
    $output\"\n      exit 1\n  fi\nfi\n}\n\nsync_spin_to_bitbucket(){\n  setup_git\n
    \ sync_spin_to_git\n  if [[ $merge_branch == \"true\" && $target_branch != \"\"
    && ($git_branch != $target_branch)  ]];then\n    if [[ $git_api_url_port != \"\"
    ]];then\n      git_bitbucket_api=$git_bitbucket_api:$git_api_url_port\n      create_pr_bitbucket\n
    \     if [[ $auto_merge == \"true\" ]]; then\n        approve_pr_bitbucket\n        sleep
    5\n        merge_pr_bitbucket\n      fi\n    else\n      create_pr_bitbucket\n
    \     if [[ $auto_merge == \"true\" ]]; then\n        approve_pr_bitbucket\n        sleep
    5\n        merge_pr_bitbucket\n      fi\n    fi\n  fi\n}\n"
  deployer.sh: "#!/bin/bash\necho \"In deployer.sh\"\nSBASE=scripts\nsource config/repo.properties\nsource
    $SBASE/spin.sh\nsource $SBASE/stash.sh\nsource $SBASE/s3.sh\nsource $SBASE/github.sh\nsource
    $SBASE/bitbucket.sh\necho \"Sourcing complete\"\nsync_repo_from_spinnaker(){\n\tif
    [[ $repo_type = \"s3\" ]];\n \tthen\n\t   upload_spin_to_s3\n\telif [[ $repo_type
    = \"stash\" ]]; then\n\t\tsync_spin_to_stash\n  elif [[ $repo_type == \"bitbucket\"
    ]]; then\n\t\tsync_spin_to_bitbucket\n\telif [[ $repo_type = \"git\" ]]; then\n\t\tsync_spin_to_github\n\tfi\n}\nsync_spinnaker_from_repo(){\n\tif
    [[ $repo_type = \"s3\" ]];\n \tthen\n\t   sync_from_s3_spin\n\telif [[ $repo_type
    = \"stash\" || $repo_type = \"git\" || $repo_type = \"bitbucket\" ]]; then\n\t\tsync_git_to_spin\n\tfi\n}\n\nif
    [[ \"$command\" == \"download\" ]]; then\n\tsync_spinnaker_from_repo\nelif [[
    \"$command\" == \"upload\" ]]; then\n        echo \"executing upload\"\n\t#statement\n\tsync_repo_from_spinnaker\nelse\n\techo
    \"ERROR: unknown command\"\n\nfi\necho \"Done executing\"\n"
  git.sh: "#!/bin/bash\nsource scripts/spin.sh\n\ngit_repo=$repo_name\ntempdir=\"/tmp/\"\npull_requred=false\nif [[ $git_branch == \"\" ]]\nthen\ngit_branch=\"master\"\nfi\nsetup_git()
    {\n  echo \"Setting up the Git \"\n  local name=${git_user:-spinnaker}\n  local
    email=${git_user_email:-spinnaker@symphony.com}\n  git config --global user.email
    \"$email\"\n  git config --global user.name \"$name\"\n  {{ .Values.spinnaker.gitopsHalyard.pipelinePromotion.gitConfig }} \n}\n  git_clone_http() {\n
    \ echo \"cloning $git_project/$git_repo over https\"\n  if [[ $repo_type == \"git\"
    || $repo_type == \"bitbucket\" ]]; then\n    clone_result=$(git clone https://$git_user:${git_secret_token}@${git_url}/${git_project}/${git_repo}.git
    $tempdir/$git_repo)\n  elif [[ $repo_type == \"stash\" ]]; then\n    #statements\n
    \   if [[ $git_url_port != \"\" ]]; then\n      clone_result=$(git  clone https://$git_user:${git_secret_token}@${git_url}:$git_url_port/scm/${git_project}/$git_repo.git
    $tempdir/$git_repo)\n    else\n      clone_result=$(git  clone https://$git_user:${git_secret_token}@${git_url}/scm/${git_project}/$git_repo.git
    $tempdir/$git_repo)\n    fi\n  fi\n  echo $clone_result\n}\ngit_clone_ssh(){\n
    \ echo \"cloning $git_project/$git_repo over ssh\"\n  if [[ $repo_type == \"git\"
    || $repo_type == \"bitbucket\" ]]\n  then\n    clone_result=$(git clone git@${git_url}:${git_project}/$git_repo.git
    $tempdir/$git_repo)\n  elif [[ $repo_type == \"stash\" && $git_url_port != \"\"
    ]]; then\n    #statements\n    clone_result=$(git clone ssh://git@${git_url}:$git_url_port/${git_project}/$git_repo.git
    $tempdir/$git_repo )\n  else\n\n    clone_result=$(git clone ssh://git@${git_url}:${git_project}/$git_repo.git
    $tempdir/$git_repo $tempdir/$git_repo)\n  fi\n  echo $clone_result\n}\n\ngit_add_file()
    {\n  local file=$1\n  git add $file\n}\n\ngit_add_all() {\n  git add $1\n}\ngit_tag_all()
    {\n  git tag -a Backup-$TAGSTAMP -m \"$msg\"\n  git push --tags\n}\n\ngit_delete_file()
    {\n  local file=$1\n  git rm $file\n}\n\ngit_checkout_branch(){\n  all_branches=$(git
    branch -r| grep -w  origin/$git_branch)\n  echo $all_lbranches\n  if [[ $all_branches
    != \"\" ]]\n  then\n    branch_checkout_result=$(git checkout $git_branch)\n    echo
    $branch_checkout_result\n    pull_requred=true\n  else\n    git checkout -b $git_branch\n
    \ fi\n\n}\ngit_add_all(){\n\n\tgit add $1\n\n}\ngit_commit_all() {\n  local branch=$git_branch\n
    \ local msg=\"checking application and pipeline raw data\"\n if [ \"$pull_requred\"
    = true ]; then\n   git pull origin $branch --no-edit\n   if [ \"$?\" != \"0\"
    ];then\n     echo \"[ERROR]: Failed to pull $branch upstream.\"\n     exit 1\n
    \ fi\nfi\n  opts=\"\"\n  if [ \"$git_commit_sign\" == \"true\" ]; then\n    opts=\"-s\"\n
    \ fi\n  #git commit $opts -a -m $msg\n  git commit -m \"$msg\"\n  git push --set-upstream
    origin $branch\n  if [ \"$?\" != \"0\" ];then\n    echo \"[ERROR]: Failed to push
    $branch upstream.\"\n    exit 1\n  fi\n}\n\nsync_spin_to_git() {\n\n  echo \"In
    upload function which copies spinnaker application and pipeline from spinnaker
    to repo\"\n\n  local user_root_folder=$root_folder\n\n  if [ \"$git_secret_sshkey\"
    != \"\" ]; then\n    git_clone_ssh\n  elif [ \"$git_secret_token\" != \"\" ];
    then\n    git_clone_http\n  else\n    echo \"git cloning requires either a git_aws_secret_key
    to be set or git_aws_secret_token\"\n   exit 5\n  fi\n\n  projectdir=$tempdir/$git_repo\n
    \ cd $projectdir\n  #We are done, get update git\n  git_checkout_branch\n  get_pipelines_data\n
    \ git_add_all $root_folder\n  git_commit_all\n  return 0\n}\nsync_git_to_spin(){\n
    \ setup_git\n  if [ \"$git_secret_sshkey\" != \"\" ]; then\n    git_clone_ssh\n
    \ elif [ \"$git_secret_token\" != \"\" ]; then\n    git_clone_http\n  else\n    echo
    \"git cloning requires either a git_aws_secret_key to be set or git_aws_secret_token\"\n
    \  exit 5\n  fi\n  projectdir=$tempdir/$git_repo\n  cd $projectdir\n  git_checkout_branch\n
    \ syncup_spin\n}\n"
  github.sh: |
    #!/bin/bash

    #this script funtions only work for github central repository

    #this script funtions only work for git repo
    #env variables needed for this to work are as below
    #***git_url="example.bitbucket.com" make sure you dont add http/https or / in the url
    #****git_repo="pipelinepromotion" repo to be pushed/download pipeline json files from
    #***git_project="kes" project key is needed to clone/push/pull merge code
    #***git_user="tes.user" user is needed for cloning and pusing changes (stash does not support only access key)
    #***git_branch="testbranch" the branch to which the code should be merged with
    #***merge_branch=false if true then provide all the below env variables
    #   git_secret_token="dafjaljoahfoasjoijso" needed to create pull requests should be the git_users secret token
    #   git_pr_token="slkdfjaljoajfopaj" this is approver token to approve pull requests / you can also provide approver password here.
    #   git_approve_user="test.approver"  username of the pull request approver
    #   git_password="adjoowddaw" make sure your password does not include special characters like # @*/. special characters cause git clone command to fail with https
    #
    #  repo_type="stash" for selfhosted bitbucket server please use stash as repo type
    #***root_folder="path/to/pipeline-promotion/folder" folder to be selected in the repo to which the pipeline jobs to be pushed
    #***command=upload for running specific job -
    #                                         upload - to upload spinnaker pipeline json files to repo
    #                                         download - to download pipeline json file from repo and apply on spinnaker
    #***spinnaker_applications="testapp,sampleapp" application needed to collect the pipeline information
    #spinnaker_pipelines="" provide pipelines to be collected, if nothing given, all the pipelines of the application are collected
    #git_secret_sshkey="sshkey" ssh key if you want to clone repo with ssh protocol

    # note *** env variables are mandatory to work with the script

    source scripts/git.sh
    git_hub_api_url=$git_api_url
    approve_pr_github(){
      approve_req=$(curl -o -I -L -s -w "%{http_code}" -X POST -H "Accept: application/vnd.github.v3+json" -u $git_approve_user:$git_pr_token  $git_hub_api_url/$git_user/${git_repo}/pulls/${pr_id}/reviews \
      -d '{"body": "Spinnaker says LGTM","event": "APPROVE"}')
      echo $approve_req
      if [[ $approve_req == "200" ]];then
        echo "merge request approved successfully"
      else
        echo "FAIL: failed to approve the request $"
        exit 1
      fi
    }

    merge_pr_github(){

      merge_req=$(curl -o -I -L -s -w "%{http_code}" -X PUT -H "Accept: application/vnd.github.v3+json" -u $git_user:$git_secret_token $git_hub_api_url/$git_user/${git_repo}/pulls/${pr_id}/merge)
      echo $merge_req
      if [[ $merge_req == "200" ]]; then
        echo "merged pr successfully"
      else
        echo "FAILED: failed to merge $merge_pr"
        exit 1
    fi
    }

    create_pr_github(){

      local output=$(curl  -X POST -H "Accept: application/vnd.github.v3+json" -u $git_user:$git_secret_token $git_hub_api_url/${git_user}/${git_repo}/pulls \
      -d '{"title": "pull request to merge '$git_branch' to master","body": "pull request to merge latest pipleine jobs information to '$target_branch'", "head": "'${git_branch}'","base": "'$target_branch'"}')
      if [ "$?" != 0 ]
      then
        echo "master branch is already up-to-date"
        exit 0
      else
        echo $output
        echo $output > pr_response.json
        errors=$(cat  pr_response.json| jq '(.errors)' | sed 's/\"//g')
        if [[ $errors != null ]]; then
          echo "ERROR: failed to raise pull request $errors"
          exit 1
        fi
        pr_id=$(cat  pr_response.json| jq '(.number)' | sed 's/\"//g')
        if [[  $pr_id != ""  ]]; then
          echo "successfully created pull request "
        else
          echo "ERROR: failed to raise pull request $output"
          exit 1
      fi
    fi
    }

    sync_spin_to_github(){
      setup_git
      sync_spin_to_git
      if [[ $merge_branch == "true" && $target_branch != "" && ($git_branch != $target_branch)  ]];then
        if [[ $git_api_url_port != "" ]];then
          git_hub_api_url=$git_hub_api_url:$git_api_url_port

          create_pr_github
          if [[ $auto_merge == "true" ]]; then
            approve_pr_github
            merge_pr_github
          fi
        else
          create_pr_github
          if [[ $auto_merge == "true" ]]; then
            approve_pr_github
            merge_pr_github
          fi
        fi
      fi
    }
  s3.sh: |
    #!/bin/bash
    source scripts/spin.sh
    absolute_path="$(dirname $(readlink -f $0))"

    # s3_folder=folder/in/s3/bucket if not given script uploads to root folder or the s3 bucket
    # ***bucket_name=testenvpipelinebucket "bucktet name to upload pipeline configuration"
    # ***AWS_ACCESS_KEY_ID="SKJGIHOBGIHIHOOH" access key to access s3 bucket
    # ***AWS_SECRET_ACCESS_KEY="sdfjlasj2e334234sdljflsjflsd98y9sy/0UVv6eCg" secret to access s3 bucket
    # ***repo_type=s3 provide repo type as s3
    #***command=upload for running specific job -
    #                                         upload - to upload spinnaker pipeline json files to repo
    #                                         download - to download pipeline json file from repo and apply on spinnaker
    #***spinnaker_applications="testapp,sampleapp" application needed to collect the pipeline information
    #spinnaker_pipelines="" provide pipelines to be collected, if nothing given, all the pipelines of the application are collected


    # note *** env variables are mandatory to work with the script
    s3_folder=$root_folder
    tempdir="/tmp/"
    bucket_name=$repo_name
    create_bucket(){
      #to create a bucket in s3 bucket name needed
            aws s3 mb s3://$bucket_name
            if [ $? != 0 ]; then
                    echo "[ERROR]: Failed to create s3 bucket  might be aleady existing"
            fi
    }

    list_bucket(){
      # to llst bucket objects
         aws s3 ls s3://$bucket_name/
             if [ $? != 0 ]; then
              echo "[ERROR]: Failed to list s3 bucket "
          fi
    }

    list_application_folder(){
      # to list an object folder
            aws ls s3://$bucket_name/${s_folder}/$1 | awk '{print $4}'
    }

    upload_spin_to_s3(){
      # get the pipeline data from spinnaker and store in root_folder
      get_pipelines_data
      #upload spinnaker pipelines data and upload to s3 folder
      aws s3 cp $tempdir/$bucket_name/$s3_folder s3://$bucket_name/$s3_folder --recursive
      if [ "$?" != 0 ]; then
              echo "[ERROR]: Failed to upload to bucket" $bucket_name
      else
              echo "uploaded to bucket successfully"
      fi
    }
    sync_from_s3_spin(){

      echo "downloading  spinnaker application pipelines configuration"

      aws s3 sync  s3://$bucket_name/$s3_folder $tempdir$s3_folder
      #apply configuration in spinnaker
      syncup_spin
    }

    delete_s3_object(){
      #delete an object in bucket
            aws rm s3://$bucket_name/${s3_folder}/${application_name}/  --recursive
            if [ $? != 0 ]; then
                    echo "[ERROR]: Failed to delete s3 application folder "
            else
                    echo "created bucket successfully"
            fi
    }
  spin.sh: "#!/bin/bash\n#source $(dirname $0)/git.sh\ntempdir=\"/tmp/\"\n\n#spinnaker_applications=\"sampleapp\"\nget_app_pipelines(){\n\tspin
    pipeline list --application $1  > tmp.json\n\tif [ \"$?\" != \"0\" ]; then\n\t\t\techo
    \"ERROR: spin pipeline list --application $1\"\n\t\t\treturn 1\n\tfi\n\tcat tmp.json
    | jq '.[] | (.name)' | sed 's/\\\"//g' > pipelines_in_application.list\n\tcat
    tmp.json | jq '.[] | (.id)' | sed 's/\\\"//g' > pipelines_guid.list\n\trm tmp.json\n}\n\n\nlive_backup_spin()
    {\n\n#This function will backup existing spinnaker data and store it in local
    for further comparison\n\n  if [[ $repo_type = \"s3\" ]]; then\n\t\tprojectdir=$tempdir/$root_folder\n\telse\n\t\tprojectdir=$tempdir/${git_repo}/$root_folder\n
    \ fi\n\tlive_projectdir_workdir=$projectdir/live_backup\n\n  if [ -d \"$live_projectdir_workdir\"
    ]\n  then\n    echo \"given live_spinnaker_project_work_dir is present\"\n  else\n
    \   echo \"given live_spinnaker_project_work_dir is not present therefore creating
    it\"\n    mkdir -p \"$projectdir/live_backup\"\n  fi\n\n  cd $live_projectdir_workdir\n\n
    \ spinnaker_app=$spinnaker_applications\n  IFS=',' read -r -a spinnaker_app_array
    <<< \"$spinnaker_app\"\n\n\n  spinnaker_pipe=$spinnaker_pipelines\n  IFS=',' read
    -r -a spinnaker_pipe_array <<< \"$spinnaker_pipe\"\n\n  for (( m=0; m<${#spinnaker_app_array[@]};
    m++ )); do\n     sourceApp=${spinnaker_app_array[$m]}\n     echo -e \"Processing
    application $sourceApp\\n\"\n     mkdir -p $sourceApp ; cd $sourceApp\n\t\t        #
    Get into the correct directory\n     spin -k pipeline list --application $sourceApp
    \ > tmp.json\n     if [ \"$?\" != \"0\" ]; then\n         echo \"ERROR: spin pipeline
    list --application $sourceApp\"\n         return 1\n     fi\n     cat tmp.json
    | jq '.[] | (.name)' | sed 's/\\\"//g' > live_pipelines_in_application.list\n
    \    cat tmp.json | jq '.[] | (.id)' | sed 's/\\\"//g' > live_pipelines_guid.list\n
    \    rm tmp.json\n\n     spin -k application get $sourceApp  > $sourceApp.json\n
    \    if [ \"$?\" != \"0\" ]; then\n         echo \"ERROR: spin application get
    $sourceApp\"\n         return 1\n     fi\n\n     if [[ ${#spinnaker_pipe_array[@]}
    > 0 ]]; then\n         for (( p=0; p<${#spinnaker_pipe_array[@]}; p++ )); do\n
    \           pipeLine=${spinnaker_pipe_array[$p]}\n            echo -e \"    Processing
    pipeline $pipeLine\\n\"\n            # Check if pipeline exists\n            existingPipe=`grep
    \\^${pipeLine}\\$ live_pipelines_in_application.list`\n            if [[ \"$existingPipe\"
    == \"${pipeLine}\" ]]; then\n               spin -k pipeline get --application
    $sourceApp  --name \"$pipeLine\" > \"$pipeLine.json\"\n               if [ \"$?\"
    != \"0\" ]; then\n                   echo \"ERROR: spin spin pipeline get --application
    $sourceApp  --name \\\"$pipeLine\\\"\"\n                   return 1\n               fi\n
    \           else\n               echo \"WARNING: pipeline=${pipeLine} not found
    in application=$sourceApp ... skipping\"\n            fi\n         done\n     else
    # No pipelines defined, get all the pipelines\n         while read -r line; do\n
    \           echo -e \"    Processing pipeline $line\\n\"\n            spin -k
    pipeline get --application $sourceApp --name \"$line\" > \"$line.json\"\n            if
    [ \"$?\" != \"0\" ]; then\n                echo \"ERROR: spin spin pipeline get
    --application $sourceApp  --name $line\"\n                return 1\n            fi\n
    \        done < live_pipelines_in_application.list\n     fi\n      cd ..\n  done\n
    \ return 0\n}\n\ndelete_odd_pipelines() {\n  #Delete the additional pielines that
    are in spinnaker and not in git\n   for (( m=0; m<${#spinnaker_app_array[@]};
    m++ )); do\n\t   sourceApp=${spinnaker_app_array[$m]}\n\t   if [ -f \"$projectdir/live_backup/$sourceApp/odd_pipeline.txt\"
    ]; then\n             if [ ! -s \"$projectdir/live_backup/$sourceApp/odd_pipeline.txt\"
    ]; then\n\t     echo \"no new pipelines to delete\"\n             else\n           echo
    \"============ Delete pipeline in $sourceApp Application =============\"\n\n\t
    \  while IFS= read -r pipelinename; do\n           echo \"Deleting the pipeline
    $pipelinename\"\n\t   spin -k pipeline delete --name $pipelinename --application
    $sourceApp\n           done < $projectdir/live_backup/$sourceApp/odd_pipeline.txt\n\n\t
    \  rm -rf $projectdir/live_backup/$sourceApp/odd_pipeline.txt\n\n   fi\n   fi\ndone\n\n}\n#Create
    default parameterconfig-files\ncreate_default_params() {\n    targetDir=${1:-default-config}\n
    \   echo \"Processing pipelines and creating output in $targetDir\"\n    mkdir
    -p $targetDir\n    for json in *.json ; do\n      [[ -f \"$json\" ]] || continue\n
    \     echo \"\tprocessing $json\"\n      cat \"$json\" | jq '.parameterConfig
    | reduce .[] as $p  ({};.Parameters += {($p.name): $p.default})'  >  $targetDir/tmp-param.json
    2>/dev/null\n      cat \"$json\" | jq '.triggers[0] '  >  $targetDir/tmp-trig.json
    2>/dev/null\n\n      if [[ `cat $targetDir/tmp-trig.json | wc -c` -gt 5 ]]\n      then\n
    \       cat $targetDir/tmp-param.json | jq '.triggerValues=$pp' --argfile pp $targetDir/tmp-trig.json
    > $targetDir/\"$json\" 2>/dev/null\n      else\n        cp  $targetDir/tmp-param.json
    $targetDir/\"$json\"\n      fi\n    done\n    rm -f $targetDir/tmp-param.json\n
    \   rm -f $targetDir/tmp-trig.json\n    #Remove all files with zero size\n    echo
    \"Removing files that do not have any parameters defined\"\n    find $targetDir
    -type f -size -4c -delete # No parameterConfig in the file\n    #find $targetDir
    -type f -size -4c -print -delete # No parameterConfig in the file\n}\n\nequate_pipelines_in_app()
    {\n\n #This function will comapre the applications and pipelines in git and spinnaker
    and gives the additional pipelines data\n\n  IFS=',' read -r -a spinnaker_app_array
    <<< \"$spinnaker_app\"\n\n  IFS=',' read -r -a spinnaker_pipe_array <<< \"$spinnaker_pipe\"\n\n
    \ for (( m=0; m<${#spinnaker_app_array[@]}; m++ )); do\n     sourceApp=${spinnaker_app_array[$m]}\n\n
    \    touch $projectdir/live_backup/$sourceApp/odd_pipeline_id.txt\n\n\t\t echo
    $projectdir\n\t\t echo $git_project_work_dir\n\t\t echo $sourceApp\n     diff
    $projectdir/$git_project_work_dir/$sourceApp/pipelines_guid.list $projectdir/live_backup/$sourceApp/live_pipelines_guid.list
    | awk '{print $2}' | sed 1d > $projectdir/live_backup/$sourceApp/odd_pipeline_id.txt\n\n
    \    #list all existing spinnaker pipelines with app as reference\n     spin -k
    pipeline list --application $sourceApp > $projectdir/live_backup/$sourceApp/$sourceApp-pipeline_list.json\n
    \    touch $projectdir/live_backup/$sourceApp/odd_pipeline.txt\n\n     while IFS=
    read -r id; do\n     #Extract the pipeline names using guids as reference\n     cat
    $projectdir/live_backup/$sourceApp/$sourceApp-pipeline_list.json | jq '.[] | select
    (.id==\"'$id'\") | .name' -r >> $projectdir/live_backup/$sourceApp/odd_pipeline.txt\n
    \    done < $projectdir/live_backup/$sourceApp/odd_pipeline_id.txt\n  done\n}\n\nsyncup_spin()
    {\n  echo \"In Download function that updates the spinnaker instance with the
    contents in repo\"\n\n  #Backup of existing spinnaker pipelines with guids\n  live_backup_spin\n\n
    \ #Compare guids of existing pipelines and pipelines in git and provide names
    of additional pipelines\n  equate_pipelines_in_app\n\n  #Delete the extra pipelines(pipelines
    in spinnaker and not in git)\n\tif [[ $delete_on_sync_spin == \"true\" ]]; then\n\t\tdelete_odd_pipelines\n\tfi\n\n\tif
    [[ $repo_type = \"s3\" ]]; then\n\t\tprojectdir=$tempdir/$root_folder\n\t\techo
    \"project dir at synup spin $projectdir\"\n\telse\n\n\t\tprojectdir=$tempdir/${git_repo}/$root_folder\n\tfi\n
    \ if [ -d \"$projectdir\" ]\n  then\n    echo \"given git_project_work_dir is
    present\"\n  else\n    echo \"given git_project_work_dir is not present therefore
    creating it\"\n    mkdir -p \"$projectdir/$git_project_work_dir\"\n  fi\n\n  cd
    $projectdir\n  spinnaker_app=$spinnaker_applications\n  IFS=',' read -r -a spinnaker_app_array
    <<< \"$spinnaker_app\"\n\n  spinnaker_pipe=$spinnaker_pipelines\n  #IFS=',' read
    -r -a spinnaker_pipe_array <<< \"k8s-deploy\"\n  IFS=',' read -r -a spinnaker_pipe_array
    <<< \"$spinnaker_pipe\"\n\n  echo $projectdir\n  for (( m=0; m<${#spinnaker_app_array[@]};
    m++ )); do\n     sourceApp=${spinnaker_app_array[$m]}\n     echo -e \"Processing
    application $sourceApp\\n\"\n     cd $sourceApp              # Get into the correct
    directory\n     if [ \"$?\" != \"0\" ]; then\n         echo \"ERROR: Unable to
    change to application directory: $sourceApp\"\n         return 1\n     fi\n\n
    \    #Create the application by default, we can have flag to for this later\n
    \    spin -k application save -f $sourceApp.json\n     retVal=$?\n     if [[ \"$retVal\"
    != \"0\" && \"$ignore_errors\" == \"false\" ]]; then\n         echo \"ERROR: spin
    application save $sourceApp\"\n         return 1\n     elif [[ \"$retVal\" !=
    \"0\" && \"$ignore_errors\" == \"true\" ]]; then\n         echo \"ERROR: spin
    application save $sourceApp, continuing\"\n         cd ..\n         continue\n
    \    fi\n     #sleep 30 # Give a few seconds after application creation\n\n     if
    [[ ${#spinnaker_pipe_array[@]} > 0 ]]; then\n         for (( p=0; p<${#spinnaker_pipe_array[@]};
    p++ )); do\n            pipeLine=${spinnaker_pipe_array[$p]}\n            echo
    -e \"    Processing pipeline $pipeLine\\n\"\n            # Check if pipeline file
    \ exists\n            if [ -f \"$pipeLine.json\" ]; then\n                #Update
    parameterConfig\n                if [[ \"$pipelineconfig\" == \"true\" ]]; then\n\n
    \                   mkdir -p temp\n                    update_params \"$pipeLine.json\"\n
    \                   rm -rf temp\n                fi\n               spin -k pipeline
    save --file \"$pipeLine.json\"\n               retVal=$?\n               if [[
    \"$retVal\" != \"0\" && \"$ignore_errors\" == \"false\" ]]; then\n                   echo
    \"ERROR: spin pipeline save --file $pipeLine.json\"\n                   return
    1\n               elif [[ \"$retVal\" != \"0\" && \"$ignore_errors\" == \"true\"
    ]]; then\n                   echo \"ERROR: spin pipeline save --file $pipeLine.json,
    continuing\"\n                   continue\n               fi\n            else\n
    \              echo \"WARNING: pipeline=${pipeLine} not found in application=$sourceApp
    ... skipping\"\n            fi\n         done\n     else # No pipelines defined,
    get all the pipelines\n         while read -r line; do\n            [[ -f \"$line.json\"
    ]] || continue\n            pipeLine=$line\n            echo -e \"    Processing
    pipeline $pipeLine\\n\"\n\n            #Update parameterConfig\n            if
    [[ \"$pipelineconfig\" == \"true\" ]]; then\n\t\t\t\t\t\t\techo \"in pipelineconfig
    else\"\n                mkdir -p temp\n                update_params \"$pipeLine.json\"\n
    \               #rm -rf temp\n            fi\n\n            echo `realpath $pipeLine.json`\n\t\t\t\t\t\tif
    test -f \"$pipeLine.json\"; then\n\t\t\t\t\t\t\tspin -k pipeline save --file \"$pipeLine.json\"\n\t\t\t\t\t\tfi\n\n
    \           retVal=$?\n            if [[ \"$retVal\" != \"0\" && \"$ignore_errors\"
    == \"false\"  ]]; then\n                echo \"ERROR: spin pipeline save --file
    $pipeLine.json\"\n                return 1\n            elif [[ \"$retVal\" !=
    \"0\" && \"$ignore_errors\" == \"true\" ]]; then\n                echo \"ERROR:
    spin pipeline save --file $pipeLine.json, continuing\"\n                continue\n
    \           fi\n           sleep 5 # Slow it down\n         done < pipelines_in_application.list\n
    \    fi\n     cd ..\n  done\n\n}\nget_pipelines_data(){\n\t      spinnaker_app=$spinnaker_applications\n
    \       IFS=',' read -r -a spinnaker_app_array <<< \"$spinnaker_app\"\n        spinnaker_pipe=$spinnaker_pipelines\n
    \       #IFS=',' read -r -a spinnaker_pipe_array <<< \"k8s-deploy\"\n        IFS=','
    read -r -a spinnaker_pipe_array <<< \"$spinnaker_pipe\"\n\n\t\t\t\tif [[ $root_folder
    == \"\" ]]; then\n\t\t\t\t\troot_folder=\".\"\n\t\t\t\tfi\n        for (( m=0;
    m<${#spinnaker_app_array[@]}; m++ )); do\n     sourceApp=${spinnaker_app_array[$m]}\n
    \    echo -e \"Processing application $sourceApp\\n\"\n\n\t\t echo \"get pipelines
    data $root_folder\"\n     mkdir -p $tempdir/$git_repo/${root_folder}/$sourceApp
    ; cd $tempdir/$git_repo/${root_folder}/$sourceApp              # Get into the
    correct directory\n\n     get_app_pipelines $sourceApp\n     spin application
    get $sourceApp  > $sourceApp.json\n     if [ \"$?\" != \"0\" ]; then\n         echo
    \"ERROR: spin application get $sourceApp\"\n         return 1\n     fi\n     if
    [[ ${#spinnaker_pipe_array[@]} > 0 ]]; then\n         for (( p=0; p<${#spinnaker_pipe_array[@]};
    p++ )); do\n            pipeLine=${spinnaker_pipe_array[$p]}\n            echo
    -e \"    Processing pipeline $pipeLine\\n\"\n            # Check if pipeline exists\n
    \           existingPipe=`grep \\^${pipeLine}\\$ pipelines_in_application.list`\n
    \           if [[ \"$existingPipe\" == \"${pipeLine}\" ]]; then\n               spin
    pipeline get --application $sourceApp  --name \"$pipeLine\" > \"$pipeLine.json\"\n\n
    \              if [ \"$?\" != \"0\" ]; then\n                   echo \"ERROR:
    spin spin pipeline get --application $sourceApp  --name \\\"$pipeLine\\\"\"\n
    \                  return 1\n               fi\n            else\n               echo
    \"WARNING: pipeline=${pipeLine} not found in application=$sourceApp ... skipping\"\n
    \           fi\n         done\n     else # No pipelines defined, get all the pipelines\n
    \        while read -r line; do\n            echo -e \"    Processing pipeline
    $line\\n\"\n            spin pipeline get --application $sourceApp --name \"$line\"
    > \"$line.json\"\n            if [ \"$?\" != \"0\" ]; then\n                echo
    \"ERROR: spin spin pipeline get --application $sourceApp  --name $line\"\n                return
    1\n            fi\n\n         done < pipelines_in_application.list\n     fi\n
    \    if [[ \"$pipelinecreateconf\" == \"true\" ]]; then\n        create_default_params\n
    \    fi\n     cd -\n  done\n}\n\ndownload_spin() {\n  echo \"In Download function
    that updates the spinnaker instance with the contents in git\"\n  local user_root_folder=$root_folder\n\n
    \ if [ \"$git_secret_sshkey\" != \"\" ]; then\n    git_clone_ssh_change $user_root_folder
    $git_repo $git_project\n  elif [ \"$git_secret_token\" != \"\" ]; then\n    git_clone_http
    $user_root_folder $git_repo $git_project\n  else\n    echo \"git cloning requires
    either a git_secret_sshkey to be set or git_secret_token\"\n   exit 5\n  fi\n\n
    \ projectdir=$HOME/$git_project\n  cd $projectdir\n\n  spinnaker_app=$spinnaker_applications\n
    \ IFS=',' read -r -a spinnaker_app_array <<< \"$spinnaker_app\"\n\n  spinnaker_pipe=$spinnaker_pipelines\n
    \ #IFS=',' read -r -a spinnaker_pipe_array <<< \"k8s-deploy\"\n  IFS=',' read
    -r -a spinnaker_pipe_array <<< \"$spinnaker_pipe\"\n\n\n  for (( m=0; m<${#spinnaker_app_array[@]};
    m++ )); do\n     sourceApp=${spinnaker_app_array[$m]}\n     echo -e \"Processing
    application $sourceApp\\n\"\n     cd $sourceApp              # Get into the correct
    directory\n     if [ \"$?\" != \"0\" ]; then\n         echo \"ERROR: Unable to
    change to application directory: $sourceApp\"\n         return 1\n     fi\n\n
    \    #Create the application by default, we can have flag to for this later\n
    \    spin application save -f $sourceApp.json\n     retVal=$?\n     if [[ \"$retVal\"
    != \"0\" && \"$ignore_errors\" == \"false\" ]]; then\n         echo \"ERROR: spin
    application save $sourceApp\"\n         return 1\n     elif [[ \"$retVal\" !=
    \"0\" && \"$ignore_errors\" == \"true\" ]]; then\n         echo \"ERROR: spin
    application save $sourceApp, continuing\"\n         cd ..\n         continue\n
    \    fi\n     sleep 30 # Give a few seconds after application creation\n\n     if
    [[ ${#spinnaker_pipe_array[@]} > 0 ]]; then\n         for (( p=0; p<${#spinnaker_pipe_array[@]};
    p++ )); do\n            pipeLine=${spinnaker_pipe_array[$p]}\n            echo
    -e \"    Processing pipeline $pipeLine\\n\"\n            # Check if pipeline file
    \ exists\n            if [ -f \"$pipeLine.json\" ]; then\n                #Update
    parameterConfig\n                if [[ \"$pipelineconfig\" == \"true\" ]]; then\n
    \                   mkdir -p temp\n                    update_params \"$pipeLine.json\"\n
    \                   rm -rf temp\n                fi\n               spin pipeline
    save --file \"$pipeLine.json\"\n               retVal=$?\n               if [[
    \"$retVal\" != \"0\" && \"$ignore_errors\" == \"false\" ]]; then\n                   echo
    \"ERROR: spin pipeline save --file $pipeLine.json\"\n                   return
    1\n               elif [[ \"$retVal\" != \"0\" && \"$ignore_errors\" == \"true\"
    ]]; then\n                   echo \"ERROR: spin pipeline save --file $pipeLine.json,
    continuing\"\n                   continue\n               fi\n            else\n
    \              echo \"WARNING: pipeline=${pipeLine} not found in application=$sourceApp
    ... skipping\"\n            fi\n         done\n     else # No pipelines defined,
    get all the pipelines\n         while read -r line; do\n            [[ -f \"$line.json\"
    ]] || continue\n            pipeLine=$line\n            echo -e \"    Processing
    pipeline $pipeLine\\n\"\n\n            #Update parameterConfig\n            if
    [[ \"$pipelineconfig\" == \"true\" ]]; then\n                mkdir -p temp\n                update_params
    \"$pipeLine.json\"\n                #rm -rf temp\n            fi\n            spin
    pipeline save --file \"$pipeLine.json\"\n            retVal=$?\n            if
    [[ \"$retVal\" != \"0\" && \"$ignore_errors\" == \"false\"  ]]; then\n                echo
    \"ERROR: spin pipeline save --file $pipeLine.json\"\n                return 1\n
    \           elif [[ \"$retVal\" != \"0\" && \"$ignore_errors\" == \"true\" ]];
    then\n                echo \"ERROR: spin pipeline save --file $pipeLine.json,
    continuing\"\n                continue\n            fi\n            sleep 5 #
    Slow it down\n         done < pipelines_in_application.list\n     fi\n     cd
    ..\n  done\n\n}\n\nupdate_params() {\n    confDir=${pipelineconfigdir}\n    if
    [ ! -d \"$confDir\" ] ; then\n      echo \"Directory specified for configuratio
    ($confDir) not found in application directory\"\n      return\n    fi\n    if
    [ ! -f \"$confDir/$json\" ] ; then\n      echo \"INFO: No configuration found
    for $json in $confDir\"\n      return\n    fi\n    json=\"$1\"\n    echo \"Processing
    pipeline ($json) and updating pipelines as per configuration in $confDir\"\n    #Extract
    .parameterConfig\n    cat \"$json\" | jq '.parameterConfig' > temp/\"config-$json\"\n
    \   #Replace parameters\n    cat temp/\"config-$json\" | jq -f /home/opsmx/scripts/replace-params.jq
    --argfile pp $confDir/\"$json\" > temp/\"updated-config-$json\"\n\n    #Replace
    .parameterConfig\n    cat \"$json\" | jq  '.parameterConfig=$uc' --argfile uc
    temp/\"updated-config-$json\" > temp/\"$json\"\n\n    ########################################################################\n
    \   #Extract 1st trigger\n    cat  temp/\"$json\"| jq '.triggers[0]' > temp/tmp-trig.json\n
    \   #Update first trigger\n    cat temp/tmp-trig.json | jq 'if $pp.triggerValues
    != null then . * $pp.triggerValues else . end'  --argfile pp $confDir/\"$json\"
    \ > temp/updated-tmp-trig.json\n    #Update pipeline-json with updated trigger\n
    \   if [[ `cat temp/updated-tmp-trig.json | wc -c` -gt 5 ]]\n    then\n      cat
    temp/\"$json\" | jq '.triggers[0]=$pp' --argfile pp temp/updated-tmp-trig.json
    > temp/final-replaced.json\n      cp temp/final-replaced.json \"$json\"\n    else\n
    \     cp  temp/\"$json\" \"$json\"\n    fi\n    ########################################################################\n}\n"
  stash.sh: "#!/bin/bash\n\n#this script funtions only work for self hosted bitbucketserver/stash
    central repository\n#env variables needed for this to work are as below\n#***git_url=\"example.bitbucket.com\"
    make sure you dont add http/https or / in the url\n#****git_repo=\"pipelinepromotion\"
    repo to be pushed/download pipeline json files from\n#***git_project=\"kes\" project
    key is needed to clone/push/pull merge code\n#***git_user=\"tes.user\" user is
    needed for cloning and pusing changes (stash does not support only access key)\n#git_password=\"adjoowddaw\"
    make sure your password does not include special characters like # @*/. special
    characters cause git clone command to fail with https\n#***git_branch=\"testbranch\"
    the branch to which the code should be merged with\n#***merge_branch=false if
    true then provide all the below env variables\n#   git_secret_token=\"dafjaljoahfoasjoijso\"
    needed to create pull requests should be the git_users secret token\n#   git_pr_token=\"slkdfjaljoajfopaj\"
    this is approver token to approve pull requests / you can also provide approver
    password here.\n#   git_approve_user=\"test.approver\"  username of the pull request
    approver\n#\n# repo_type=\"stash\" for selfhosted bitbucket server please use
    stash as repo type\n#***root_folder=\"path/to/pipeline-promotion/folder\" folder
    to be selected in the repo to which the pipeline jobs to be pushed\n#***command=upload
    for running specific job -\n#                                         upload -
    to upload spinnaker pipeline json files to repo\n#                                         download
    - to download pipeline json file from repo and apply on spinnaker\n#***spinnaker_applications=\"testapp,sampleapp\"
    application needed to collect the pipeline information\n#spinnaker_pipelines=\"\"
    provide pipelines to be collected, if nothing given, all the pipelines of the
    application are collected\n#git_secret_sshkey=\"sshkey\" ssh key if you want to
    clone repo with ssh protocol\n\n# note *** env variables are mandatory to work
    with the script\n\nsource scripts/git.sh\ngit_repo=$repo_name\npr_id=0\npr_version=0\napprove_pr_stash(){\n
    \ approve_req=$(curl -k -o -I -L -s -w \"%{http_code}\"  -X POST -H \"Content-Type:
    application/json\" -u $git_approve_user:$git_pr_token \\\n  https://$git_api_url/${git_project}/repos/${git_repo}/pull-requests/${pr_id}/approve)\n
    \ echo $approve_req\n  if [[ $approve_req == \"200\" ]];then\n    echo \"merge
    request approved successfully\"\n  else\n    echo \"FAIL: failed to approve the
    request \"\n    exit 1\n  fi\n}\n\nmerge_pr_stash(){\n\n  merge_req=$(curl -k
    -o -I -L -s -w \"%{http_code}\"  -X POST -H \"Content-Type: application/json\"
    -u $git_user:$git_secret_token   \\\n  https://$git_api_url/${git_project}/repos/${git_repo}/pull-requests/${pr_id}/merge?version=$pr_version)\n
    \ echo $merge_req\n  if [ $merge_req == \"200\" ]; then\n    echo \"merged pr
    successfully\"\n  else\n    echo \"FAILED: failed to merge $merge_pr\"\n    exit
    1\nfi\n}\ncreate_pr_stash(){\n\n\tlocal output=$(curl -k -X POST -H \"Content-Type:
    application/json\" -u $git_user:$git_secret_token   https://$git_api_url/${git_project}/repos/${git_repo}/pull-requests
    -d '{\n    \"title\": \"merging '\"$git_branch\"' to '\"$target_branch\"'\",\n
    \   \"description\": \"changes from spinnaker pipeline jobs are to be merged to
    master\",\n    \"state\": \"OPEN\",\n    \"open\": true,\n    \"closed\": false,\n
    \   \"fromRef\": {\n        \"id\": \"refs/heads/'\"${git_branch}\"'\",\n        \"repository\":
    {\n            \"slug\": \"'\"${git_repo}\"'\",\n            \"name\": null,\n
    \           \"project\": {\n                \"key\": \"'\"${git_project}\"'\"\n
    \           }\n        }\n    },\n    \"toRef\": {\n        \"id\": \"refs/heads/'\"$target_branch\"'\",\n
    \       \"repository\": {\n            \"slug\": \"'\"${git_repo}\"'\",\n            \"name\":
    null,\n            \"project\": {\n                \"key\": \"'\"${git_project}\"'\"\n
    \           }\n        }\n    },\n    \"locked\": false\n}')\n  echo $output\n
    \ echo $output > pr_response.json\n  grep  \"is already up-to-date with branch\"
    pr_response.json\n  if [ \"$?\" = 0 ]\n  then\n    echo \"master branch is already
    up-to-date\"\n    exit 0\n  else\n    pr_id=$(cat  pr_response.json| jq '(.id)'
    | sed 's/\\\"//g')\n    pr_version=$(cat pr_response.json | jq '(.version)' |
    sed 's/\\\"//g')\n\n    if [ $? = 0 ]; then\n      echo \"successfully created
    pull request \"\n      #rm -f pr_response.json\n    else\n      echo \"ERROR:
    failed to raise pull request $output\"\n      exit 1\n  fi\nfi\n}\n\nsync_spin_to_stash(){\n
    \ #setup git configuration using email and username\n  setup_git\n  #upload spinnaker
    configuration to git\n  sync_spin_to_git\n  #check if custom port is being used
    for repo\n  if [[ $merge_branch == \"true\" && $target_branch != \"\" && ($git_branch
    != $target_branch)  ]];then\n    if [[ $git_api_url_port != \"\" ]];then\n      git_api_url=$git_api_url:$git_api_url_port\n
    \     create_pr_stash\n      if [[ $auto_merge == \"true\" ]]; then\n        approve_pr_stash\n
    \       merge_pr_stash\n      fi\n    else\n      create_pr_stash\n      if [[
    $auto_merge == \"true\" ]]; then\n        approve_pr_stash\n        merge_pr_stash\n
    \     fi\n    fi\n  fi\n}\n"
kind: ConfigMap
metadata:
  name: pipe-promot-scripts
