#!/bin/bash

# Variables.
gocd_backup_api_call="{{ GO_SERVER_BACKUP_API_URL }}"
gocd_username="{{ GO_SERVER_BACKUP_USERNAME }}"
gocd_password="{{ GO_SERVER_BACKUP_PASSWORD }}"
gocd_backup_location="{{ GO_SERVER_BACKUP_TMP_LOCATION }}"
s3_backup_bucket="{{ GO_SERVER_BACKUP_S3_BUCKET }}"
snitch_url="{{ GO_SERVER_BACKUP_SNITCH_URL }}"
gocd_backup_base="gocd-{{ GO_SERVER_BACKUP_ENVIRONMENT }}"

# Trigger the backup and capture the backup path.
# The output of the api call is documented here:
#   https://api.go.cd/current/#create-a-backup
# Below is an example of the API output:
# {
#   "_links": {
#     "doc": {
#       "href": "http://api.go.cd/#backups"
#     }
#   },
#   "time": "2015-08-07T10:07:19.868Z",
#   "path": "/var/lib/go-server/serverBackups/backup_20150807-153719",
#   "user": {
#     "_links": {
#       "doc": {
#         "href": "http://api.go.cd/#users"
#       },
#       "self": {
#         "href": "https://ci.example.com/go/api/users/username"
#       },
#       "find": {
#         "href": "https://ci.example.com/go/api/users/:login_name"
#       }
#     },
#     "login_name": "username"
#   }
# }
backup_path=\
$(curl -sS "$gocd_backup_api_call" \
    -u "$gocd_username:$gocd_password" \
    -H 'Accept: application/vnd.go.cd.v1+json' \
    -X POST | \
jq .path | tr -d '"')

case $backup_path in
null)
  echo "GoCD backup failed."
  exit
  ;;
*)
  echo "GoCD backup succeeded to: $backup_path"
  ;;
esac

# Make latest backup into a tarball.
backup_dir_name="$(basename "$backup_path")"
tar zcvf "$gocd_backup_location" -C "$(dirname "$backup_path")" "${backup_dir_name}"

dated_backup_filename="${gocd_backup_base}-${backup_dir_name}.tgz"

# Transfer tarball to S3 with datetime'd filename.
aws_output=$(/usr/local/bin/aws s3 cp "${gocd_backup_location}" "s3://${s3_backup_bucket}/${dated_backup_filename}" 2>&1) || (echo $aws_output && exit)
case $aws_output in
*failed*)
  echo "Backup transfer failed: $aws_output"
  exit
  ;;
*)
  echo "Backup transfer of ${dated_backup_filename} to S3 bucket $s3_backup_bucket succeeded."
  ;;
esac

# Transfer tarball to S3 with official backup filename.
aws_output=$(/usr/local/bin/aws s3 cp "${gocd_backup_location}" "s3://${s3_backup_bucket}" 2>&1) || (echo $aws_output && exit)
case $aws_output in
*failed*)
  echo "Backup transfer failed: $aws_output"
  exit
  ;;
*)
  echo "Backup transfer of $(basename "${gocd_backup_location}") to S3 bucket $s3_backup_bucket succeeded."
  # Report to Dead Man's Snitch.
  curl $snitch_url
  ;;
esac

# Remove the tarball.
rm -f "$gocd_backup_location"
