#!/bin/bash
set -u

# Get EBS volumes with Name tag of <host>-root and # <host>-hxdepots,
# e.g. perforce-01-root and perforce-01-hxdepots.  Take snapshots, and
# tag them with the current journal counter.

function msg () { echo -e "$*"; }
function errmsg () { msg "\\nError: ${1:-Unknown Error}\\n"; ExitCode=1; }
function bail () { errmsg "${1:-Unknown Error}"; exit "${2:-1}"; }

declare ThisScript="${0##*/}"
declare Version="1.1.0"
declare ThisHost=$(hostname -s)
declare VolumeBaseName=
declare VolumeName=
declare VolumeId=
declare SnapshotId=
declare Cmd=
declare -i ExitCode=0

msg "Started ${0##*/} v$Version at $(date)."

for VolumeBaseName in root hxdepots; do
   VolumeName="${ThisHost}-${VolumeBaseName}"
   VolumeId=$(aws ec2 describe-volumes --filters Name=tag:Name,Values=$VolumeName --query 'Volumes[*].{ID:VolumeId}')

   if [[ -z "$VolumeId" ]]; then
      errmsg "Could not determine VolumeId for $VolumeName. Skipping it."
      continue
   fi

   msg "Snapshotting volume $VolumeName [$VolumeId]."
   Cmd="aws ec2 create-snapshot --description Snaphot-$VolumeName --volume-id $VolumeId --query SnapshotId --output text"

   msg "Running: $Cmd"
   SnapshotId=$($Cmd)
   if [[ -n "$SnapshotId" ]]; then
      msg "Snapshot created for $VolumeName on $ThisHost with Id: $SnapshotId."
      Cmd="aws ec2 create-tags --resources $SnapshotId --tags Key=Host,Value=$ThisHost Key=Contents,Value=CheckpointsAndArchives --output text"
      if $Cmd; then
         msg "Verified: Resource tags applied."
      else
         errmsg "Failed to apply tags to Snapshot $SnapshotId."
      fi
   else
      errmsg "Failed to create snapshot for $VolumeName."
   fi
done

if [[ "$ExitCode" -eq 0 ]]; then
   msg "Processing completed OK."
else
   msg "Processing completed WITH ERRORS. Review the output above."
fi

exit $ExitCode
