#!/bin/bash

# Pure-Bash URL encoding function.
rawurlencode() {
    local string="${1}"
    local strlen=${#string}
    local encoded=""
    local pos c
    for (( pos=0 ; pos<strlen ; pos++ )); do
        c=${string:$pos:1}
        case "$c" in
            [-_.~a-zA-Z0-9] )
                encoded+="$c"
                ;;
            * )
                # Convert the character to its hexadecimal representation.
                encoded+=$(printf '%%%02X' "'$c")
                ;;
        esac
    done
    echo "$encoded"
}

# Check if running on macOS.
if [ "$(uname)" != "Darwin" ]; then
    echo "Your platform ($(uname -a)) is not supported."
    exit 1
fi

# Ensure at least one argument (the file path) is provided.
if [ $# -lt 1 ]; then
    echo "Usage: ds.sh <path to file> [optional filename]"
    exit 1
fi

# Retrieve the file path from the first argument.
FILE_PATH="$1"
if [ ! -e "$FILE_PATH" ]; then
    echo "Error: File '$FILE_PATH' does not exist."
    exit 1
fi

# Compute absolute path
DIR=$(dirname "$FILE_PATH")
BASE=$(basename "$FILE_PATH")
ABS_PATH="$(cd "$DIR" && pwd)/$BASE"

# URL-encode the file path.
ENCODED_FILE=$(rawurlencode "$ABS_PATH")

# Start constructing the URL with the encoded file parameter.
URL="dropshare5:///action/upload?file=${ENCODED_FILE}"

# If an optional name parameter is provided, encode and append it.
if [ $# -ge 2 ]; then
    CUSTOM_NAME="$2"
    ENCODED_NAME=$(rawurlencode "$CUSTOM_NAME")
    URL="${URL}&name=${ENCODED_NAME}"
fi

# Use the open command to trigger the URL scheme.
open "$URL"
