#!/bin/bash
#
# Upload the repository to Zenodo
#

ROOT_DIR=$(dirname "$0")/..
ROOT_DIR=$(realpath $ROOT_DIR)
echo "Root dir: $ROOT_DIR"

ARCHIVE_DIR=$ROOT_DIR/../nicholls-et-al-2022-emulator-changes-archive
TAR_FILE=$ROOT_DIR/../nicholls-et-al-2022-emulator-changes.tar.gz

echo "Will prepare archive in $ARCHIVE_DIR"
mkdir -p "$ARCHIVE_DIR"

# Copy most of repository

rsync -axv --delete \
    --exclude "*.env" \
    --exclude "*.ipynb_checkpoints*" \
    --exclude "data/raw" \
    --exclude "data/processed" \
    --exclude ".git" \
    --exclude "*egg-info*" \
    --exclude "*__pycache__*" \
    --exclude "*cover-letter*" \
    --exclude "paper/trackchanges-0.7.0" \
    "${ROOT_DIR}/../nicholls-et-al-2022-emulator-changes" \
    "${ARCHIVE_DIR}"

# Now archive raw AR6 emulator output
archive_tar=false
archive_tar=true


if [ "${archive_tar}" = true ]; then
    # raw ar6 output data 
    while IFS='' read -r -d '' subdir; do
      dirname=$(dirname "$subdir")
      second_dirname=$(basename $dirname)
      bname=$(basename "$subdir")

      for level in $subdir/*; do

          bname_level=$(basename "$level")
          echo "data-${second_dirname}-$bname-$bname_level.tar.gz"
          tar -C "$subdir" -czvf "data-${second_dirname}-$bname-$bname_level.tar.gz" "$bname_level"

      done

    done < <(find $ROOT_DIR/data -maxdepth 2 -mindepth 2 -type d -path "*raw*ar6-output*" -print0)

    mkdir -p $ARCHIVE_DIR/nicholls-et-al-2022-emulator-changes/data/raw/ar6-output/
    mv *.tar.gz $ARCHIVE_DIR/nicholls-et-al-2022-emulator-changes/data/raw/ar6-output/

fi

if [ -f .env ]
then
  # thank you https://stackoverflow.com/a/20909045
  echo "Reading .env file"
  export $(grep -v '^#' .env | xargs)
fi

PROTOCOL_METADATA_FILE="nicholls-et-al-2022-emulator-changes-metadata.json"
DEPOSITION_ID_OLD="6584386"

DEPOSITION_ID=$(openscm-zenodo create-new-version "${DEPOSITION_ID_OLD}" "${PROTOCOL_METADATA_FILE}" --zenodo-url zenodo.org)
echo "DEPOSITION_ID = ${DEPOSITION_ID}"

BUCKET_ID=$(openscm-zenodo get-bucket ${DEPOSITION_ID} --zenodo-url zenodo.org)
echo "BUCKET_ID = ${BUCKET_ID}"

cd ${ARCHIVE_DIR} && find -type f -exec openscm-zenodo upload {} "${BUCKET_ID}" --zenodo-url zenodo.org --root-dir "${ROOT_DIR_TO_STRIP}" \;
# cd ${ARCHIVE_DIR} && find -type f -exec echo "Would upload {}" \;
