#!/usr/bin/env sh

### Variables
TYPE="$1"
USER="$2"
MOUNT="$3"

### Mount variables
if [ "$TYPE" = 'user' ]; then
  MOUNT_REF="$USER-$MOUNT"
  MOUNT_LOWERCASE="user/$USER-$MOUNT"
else
  MOUNT_REF="$MOUNT"
  MOUNT_LOWERCASE="$(echo "$MOUNT" | tr "[:upper:]" "[:lower:]")"
fi

### Path definitions
if [ "$TYPE" = 'user' ]; then
  if [ -d /Applications ] && [ -d /System ]; then
    USER_FOLDER='Users'
  else
    USER_FOLDER='home'
  fi
  CACHE_FOLDER="/$USER_FOLDER/$USER/.cache/rclone"
  CONFIG_FOLDER="/$USER_FOLDER/$USER/.config/rclone"
  LOG_FOLDER="/$USER_FOLDER/$USER/.local/share/rclone"
  LOG_FILE="$LOG_FOLDER/$MOUNT.log"
  MOUNT_PATH="/$USER_FOLDER/$USER/.local/mnt/$MOUNT"
else
  CACHE_FOLDER="/var/cache/rclone/$MOUNT"
  CONFIG_FOLDER="/etc"
  LOG_FOLDER="/var/log/rclone"
  LOG_FILE="$LOG_FOLDER/$MOUNT.log"
  if [ -d /Applications ] && [ -d /System ]; then
    MNT_FOLDER='Volumes'
  else
    MNT_FOLDER='mnt'
  fi
  MOUNT_PATH="/$MNT_FOLDER/$MOUNT"
fi

### Ensure folders exist
for FOLDER in "$CACHE_FOLDER" "$CONFIG_FOLDER" "$LOG_FOLDER" "$MOUNT_PATH"; do
    if [ ! -d "$FOLDER" ]; then
        mkdir -p "$FOLDER" || sudo mkdir -p "$FOLDER"
        sudo chmod 755 "$FOLDER"
        if command -v own > /dev/null; then
          sudo own "$FOLDER"
        else
          sudo chown -Rf rclone:rclone "$FOLDER" 2> /dev/null || sudo chown -Rf rclone:$(id -g -n) "$FOLDER"
        fi
    fi
done

### Define rcloneignore location
RCLONE_IGNORE="$CONFIG_FOLDER/rcloneignore"
if [ ! -f "$RCLONE_IGNORE" ] && [ -f "/etc/rcloneignore" ]; then
  RCLONE_IGNORE='/etc/rcloneignore'
fi

### Mount
unset AWS_CA_BUNDLE
export PATH="$PATH:/usr/local/bin:/usr/bin"
# TODO: Only launch with --rc-web-gui if the servers hostname is the {{ .kubernetesHost }}
# TODO: Add more secure authentication method
sudo rclone --config "$CONFIG_FOLDER/rclone.conf" \
  mount \
  --allow-other \
  --buffer-size 4G \
  --bwlimit 40M \
  --cache-chunk-path "$CACHE_FOLDER/$MOUNT_REF-chunks" \
  --cache-db-path "$CACHE_FOLDER/$MOUNT_REF-db" \
  --cache-dir "$CACHE_FOLDER/$MOUNT_REF-vfs" \
  --cache-info-age 60m \
  --cache-tmp-upload-path "$CACHE_FOLDER/$MOUNT_REF-upload" \
  --cache-workers 8 \
  --cache-writes \
  --checkers 16 \
  --dir-cache-time 24h \
  --dir-cache-time 60m \
  --drive-use-trash \
  --exclude-from "$RCLONE_IGNORE" \
  --log-file "$LOG_FILE" \
  --log-level INFO \
  --no-modtime \
  --noapplexattr \
  --poll-interval 15s \
  --stats 0 \
  --vfs-cache-max-age 1000h \
  --vfs-cache-max-size 5G \
  --vfs-cache-mode full \
  --vfs-cache-poll-interval 30s \
  --vfs-fast-fingerprint \
  --vfs-read-ahead 128M \
  --vfs-read-chunk-size 16M \
  --vfs-read-chunk-size-limit 128M \
  --volname "$MOUNT_REF" \
  "$MOUNT_REF":"$MOUNT_LOWERCASE" "$MOUNT_PATH"
