#!/usr/bin/env bash
# Ejecuta con Bash; no contiene ni renueva credenciales.
set -euo pipefail
umask 077

log() {
  printf '%s %s\n' "$(date -u '+%Y-%m-%dT%H:%M:%SZ')" "$1"
}
fail() {
  log "ERROR: $1" >&2
  exit "$2"
}

# La copia del script vive en aws-s3/sync/scripts/.
BASE_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/.." && pwd -P)"
[[ "${BASE_DIR##*/}" == sync && "${BASE_DIR%/sync}" == */aws-s3 ]] \
  || fail 'Ubicacion del laboratorio no valida.' 2
[[ -n "${HOME:-}" && -d "$HOME/.aws" ]] \
  || fail 'Falta el directorio privado de configuracion AWS.' 2
[[ -f "$BASE_DIR/bucket.txt" && ! -L "$BASE_DIR/bucket.txt" ]] \
  || fail 'Falta bucket.txt regular dentro del laboratorio.' 2
BUCKET="$(< "$BASE_DIR/bucket.txt")"
[[ "$BUCKET" =~ ^aws-s3-sync-[a-z0-9][a-z0-9-]*[a-z0-9]$ && ${#BUCKET} -le 63 ]] \
  || fail 'Destino no permitido: debe ser el bucket propio aws-s3-sync-.' 2
[[ -d "$BASE_DIR/origen" && ! -L "$BASE_DIR/origen" ]] \
  || fail 'Falta la carpeta origen o es un enlace simbolico.' 2
AWS_BIN="$(command -v aws)" || fail 'No se encuentra AWS CLI.' 2
[[ "$AWS_BIN" == /* && -x "$AWS_BIN" ]] || fail 'AWS CLI no es un ejecutable valido.' 2

# Evita mezclar las credenciales del perfil con exports de otra practica.
unset AWS_ACCESS_KEY_ID AWS_SECRET_ACCESS_KEY AWS_SESSION_TOKEN AWS_SECURITY_TOKEN
unset AWS_PROFILE AWS_DEFAULT_PROFILE AWS_CONFIG_FILE AWS_SHARED_CREDENTIALS_FILE
unset AWS_ENDPOINT_URL AWS_ENDPOINT_URL_S3 AWS_ENDPOINT_URL_STS
unset AWS_REGION AWS_DEFAULT_REGION
export AWS_PAGER="" AWS_EC2_METADATA_DISABLED=true

REGION_CONFIGURADA="$("$AWS_BIN" configure get region 2>/dev/null)" \
  || fail 'Falta la region predeterminada de AWS CLI.' 4
[[ "$REGION_CONFIGURADA" == us-east-1 ]] || fail 'La region predeterminada debe ser us-east-1.' 4

log 'Inicio de la comprobacion y sincronizacion.'
if ! "$AWS_BIN" sts get-caller-identity >/dev/null 2>&1; then
  fail 'No hay autenticacion valida; no se ha sincronizado.' 3
fi
LOCATION="$("$AWS_BIN" s3api get-bucket-location --bucket "$BUCKET" \
  --query LocationConstraint --output text 2>/dev/null)" \
  || fail 'No se puede comprobar la region del destino.' 4
[[ "$LOCATION" == None ]] || fail 'El destino no es us-east-1.' 4
if ! "$AWS_BIN" s3 sync "$BASE_DIR/origen/" "s3://$BUCKET/copias/" \
  --no-follow-symlinks --only-show-errors >/dev/null 2>&1; then
  fail 'La sincronizacion ha fallado; revisa la orden manual.' 5
fi
log 'Sincronizacion completada sin borrado remoto.'
