# Pipeline to automatically mirror
# an Azure DevOps repository in AWS CodeCommit

# Trigger on all branches
trigger:
  - 'develop'
  - 'staging'
  - 'master'

# Use latest Ubuntu image
pool:
  vmImage: 'ubuntu-latest'

variables:
  - ${{ if eq(variables['build.SourceBranchName'], 'develop') }}:
      - group: Magento-develop-cm-transportesv1
  - ${{ if eq(variables['build.SourceBranchName'], 'staging') }}:
      - group: Magento-staging-cm-transportesv1
  - ${{ if eq(variables['build.SourceBranchName'], 'master') }}:
      - group: Magento-master-cm-transportesv1

# Pipeline
steps:
  - checkout: none
  - script: |
      printenv
      # Install urlencode function to encode reserved characters in passwords
      sudo apt-get install gridsite-clients

      # Create local mirror of Azure DevOps repository
      echo "Create local mirror of Azure DevOps repository..."
      git clone --mirror --branch "${BUILD_SOURCEBRANCHNAME}" https://${AZURE_GIT_USERNAME}:$(urlencode ${AZURE_GIT_PASSWORD})@${AZURE_REPO_URL} repo-mirror

      # Sync AWS CodeCommit repository
      echo "Sync AWS CodeCommit repository..."
      cd repo-mirror
      echo "Pushing into the mirror..."
      echo "Git User: $AWS_GIT_USERNAME"
      git push --mirror https://${AWS_GIT_USERNAME}:$(urlencode ${AWS_GIT_PASSWORD})@${AWS_REPO_URL}

    displayName: 'Sync repository with AWS CodeCommit'
    env:
      AZURE_REPO_URL: $(AZURE_REPO_URL)
      AZURE_GIT_USERNAME: $(AZURE_GIT_USERNAME)
      AZURE_GIT_PASSWORD: $(AZURE_GIT_PASSWORD)
      AWS_REPO_URL: $(AWS_REPO_URL)
      AWS_GIT_USERNAME: $(AWS_GIT_USERNAME)
      AWS_GIT_PASSWORD: $(AWS_GIT_PASSWORD)
