name: docker-cp
description: "Copy a file or folder to or from a docker container or volume."
inputs:
  volume:
    description: "Name of the volume to copy to or from."
    required: true
  volumeMount:
    description: "Where to mount the volume in the container. Defaults to '/mnt'."
    required: true
    default: ""
  recreateVolume:
    description: "Delete the specified volume before creation if it exist."
    required: true
    default: "false"
  fromPath:
    description: "Path the copy from. 'volumeName:' in the path will be replaced with volumeMount. Defaults to root volume path."
    required: true
  toPath:
    description: "Path the copy to. 'volumeName:' in the path will be replaced with volumeMount. Defaults to root volume path."
    required: true
    default: ""
  containerName:
    description: "Name of the temporary docker container to create."
    required: true
    default: ${{ env.bamboo_buildResultKey || github.sha }}
  copyFlags:
    description: "Flags to use for docker cp. Use -a to copy permissions. Use -L to follow symbolic links."
    required: false
    default: ""
  image:
    description: "Docker image to run."
    required: true
    default: "busybox:latest"
  entrypoint:
    description: "Entrypoint of the docker image."
    required: false
runs:
  using: "composite"
  steps:
  - name: "Copy Files"
    run: |
      DEFAULT_PATH="${{ inputs.volume }}:/"

      FROM_PATH="${{ inputs.fromPath }}"
      if [[ -z "$FROM_PATH" ]]; then
        FROM_PATH="$DEFAULT_PATH."
      fi
      TO_PATH="${{ inputs.toPath }}"
      if [[ -z "$TO_PATH" ]]; then
        TO_PATH="$DEFAULT_PATH"
      fi

      VOLUME_MOUNT="${{ inputs.volumeMount }}"
      if [[ -z "$VOLUME_MOUNT" ]]; then
        VOLUME_MOUNT="/mnt"
      fi

      DEFAULT_REPLACEMENT="${{ inputs.containerName }}:$VOLUME_MOUNT"
      FROM_PATH=$(echo "$FROM_PATH" | sed "s|${{ inputs.volume }}:|$DEFAULT_REPLACEMENT|g")
      TO_PATH=$(echo "$TO_PATH" | sed "s|${{ inputs.volume }}:|$DEFAULT_REPLACEMENT|g")

      # Delete the volume if it exists.
      if [[ "${{ inputs.recreateVolume }}" == "true" ]] && [[ $(docker volume ls --quiet | grep -w "^${{ inputs.volume }}$" | wc -l ) -gt 0 ]]; then
        docker volume rm "${{ inputs.volume }}" --force
        echo "Deleted volume: ${{ inputs.volume }}"
      fi

      docker run --rm -d -i -v ${{ inputs.volume }}:$VOLUME_MOUNT --name ${{ inputs.containerName }} ${{ inputs.image }} ${{ inputs.entrypoint }}
      OUTPUT=$(docker cp ${{ inputs.copyFlags }} $FROM_PATH $TO_PATH 2>&1) && RESULT=$? || RESULT=$?
      echo "$OUTPUT"

      echo "Removing Temporary Container"
      docker stop ${{ inputs.containerName }} -t 0

      exit $RESULT
    shell: bash
