#!/bin/bash

# Variables
ATTACH_BUCKET=yes
DESTINATION_FOLDER="/app/bucket"
BUCKET_TYPE="${BUCKET_TYPE}"
S3_BUCKET_NAME="${S3_BUCKET_NAME}"
NB_USER="${NB_USER}"

datalake_url="${datalake_url}"
datalake_secret="${datalake_secret}"
platform_url="${platform_url}"
ATTACH_BUCKET="${ATTACH_BUCKET}"
DEFAULT_BUCKET="${DEFAULT_BUCKET}"
ACCOUNT_NAME="${ACCOUNT_NAME}"
ACCOUNT_KEY="${ACCOUNT_KEY}"
AWS_SECRET_KEY="${AWS_SECRET_KEY}"
AWS_ACCESS_KEY_ID="${AWS_ACCESS_KEY_ID}"



echo "Running Zeblok_Action ZEBLOK_ACTION=\"${ZEBLOK_ACTION}\"!"

# Attach bucket operations
if [ "$ATTACH_BUCKET" = 'yes' ]; then
  echo 'Attaching bucket'
  #mkdir -p $DESTINATION_FOLDER
  chmod 777 "$DESTINATION_FOLDER"
  if [ -n "$BUCKET_TYPE" ]; then
    if [ "$BUCKET_TYPE" = 'AZURE' ]; then
      mkdir -p /mnt/blobfusetmp
      cat > /etc/fuse_connection.yaml <<EOF
azstorage:
  account-name: ${ACCOUNT_NAME}
  endpoint: https://${ACCOUNT_NAME}.blob.core.windows.net/
  account-key: ${ACCOUNT_KEY}
  container: ${DEFAULT_BUCKET}
  mode: key
EOF
      chmod 600 /etc/fuse_connection.yaml
      #sudo sed -i '/#user_allow_other/s/^#//g' /etc/fuse.conf || echo 'user_allow_other' | sudo tee -a /etc/fuse.conf > /dev/null
      # Mount blob container using blobfuse
      blobfuse2 "$DESTINATION_FOLDER" \
               --tmp-path=/mnt/blobfusetmp \
               --config-file=/etc/fuse_connection.yaml \
               --file-cache-timeout-in-seconds=120 --use-attr-cache=true \
               --allow-other
      echo "Download complete."
    elif [ "$BUCKET_TYPE" = 'AWS' ]; then
      if [ -n "$AWS_ACCESS_KEY_ID" ] && [ -n "$AWS_SECRET_KEY" ] && [ -n "$S3_BUCKET_NAME" ]; then
        echo "${AWS_ACCESS_KEY_ID}:${AWS_SECRET_KEY}" > /root/.passwd-s3fs
        chmod 600 /root/.passwd-s3fs
        s3fs "$S3_BUCKET_NAME" "$DESTINATION_FOLDER" \
             -o passwd_file=/root/.passwd-s3fs \
             -o use_cache=/tmp -o nonempty -o allow_other -o umask=000,uid=1000,gid=100 \
             -o endpoint="$AWS_DEFAULT_REGION" # Assuming AWS_DEFAULT_REGION is set
      else
        echo "Missing AWS credentials or bucket name."
        exit 1
      fi
    else
      if [ -n "$NB_USER" ] && [ -n "$datalake_secret" ]; then
        echo "${NB_USER}:${datalake_secret}" > /root/.passwd-s3fs
        chmod 600 /root/.passwd-s3fs
        s3fs "$S3_BUCKET_NAME" "$DESTINATION_FOLDER" \
             -o url="${datalake_url}/" \
             -o use_path_request_style -o nonempty -o allow_other -o umask=000,uid=1000,gid=100 -o passwd_file=/root/.passwd-s3fs
      else
        echo "Missing NB_USER or datalake_secret."
        exit 1
      fi
    fi
  else
    echo "BUCKET_TYPE is not defined."
    exit 1
  fi
fi


