#!/bin/bash

# Create symbolic link(s) on the desktop to the object(s) selected, or to the
# enclosing directory if not.
# A script for use (only) with Nautilus.  Requires either 'zenity', or
# slight hacking to use something else.
#
# To use, copy to your ${HOME}/.gnome2/nautilus-scripts directory
#
# Please report any bugs!
#
# Author:   Jon Green < g-scripts [at] green-lines [dot] com >
# Version:  1.0

LINKS="${HOME}/Desktop"
ZENITY=zenity

warning() {
    ${ZENITY} --warning --warning-text "$*"
}

if [ ! -d "${LINKS}" ]; then
    warning "No desktop directory '${LINKS}' found - sorry."
    exit 1
fi

declare -a NAUTFILES
export IX=0
while read FILE; do
    if [ "x${FILE}" != "x" -a "x${FILE}" != 'x"' ]; then
            NAUTFILES[${IX}]="${FILE}"
            IX=$[ ${IX} + 1 ]
    fi
done <<EOF
${NAUTILUS_SCRIPT_SELECTED_FILE_PATHS[@]}
EOF

if [ 0 -eq ${IX} ]; then
    URI="${NAUTILUS_SCRIPT_CURRENT_URI}"
    METHOD="${URI:0:7}"
    if [ "file://" == "${METHOD}" ]; then
        NAUTFILES[0]="${URI:7}"
        IX=1
    fi
fi

if [ 0 == "${#NAUTFILES[@]}" ]; then
    warning "Nothing to do"
    exit
fi

for FILE in "${NAUTFILES[@]}"; do
    TAILBASE=`basename "${FILE}"`
    NEWNAME=`${ZENITY} --entry \
        --title "Enter link name" \
        --text "Enter the name of the new link for '${FILE}'" \
        --entry-text "${TAILBASE}"`
    if [ 0 -ne $? -o "x${NEWNAME}" == "x" ]; then
        warning "New name cancelled or not entered successfully"
    else
        NEWFILE="${LINKS}/${NEWNAME}"
        if [ -e "${NEWFILE}" ]; then
            warning "An object called '${NEWFILE}' exists already"
        elif ! /bin/ln -s "${FILE}" "${NEWFILE}"; then
            warning "New link could not be created"
        fi
    fi
done
