#!/usr/bin/bash
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#
#   Edd - always use your favorite text editor, anywhere.
#   Author: Petr Splichal <psplicha@redhat.com>
#
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

# Default configuration
EDD_CONFIG=${EDD_CONFIG:-~/.edd}
EDD_COMMAND=${EDD_COMMAND:-gnome-terminal --command edd}

# Allow to override with user config
[ -r "$EDD_CONFIG" ] && source "$EDD_CONFIG"

# Simple usage message
usage() {
    cat <<-EOF
	Edd - Always use your favorite text editor, anywhere.
	Usage: select, edd, paste

	Available options:
	 --last ............... open last edited text
	 --list ............... select text from history list
	 --shortcut ........... set up Alt-Shift-E keyboard shortcut
	EOF
    exit 0
}

# Set up keyboard shortcut
shortcut() {
    # Parameter: gnome
    gnome="$1"

    # Gnome 2
    if [ $gnome -eq 2 ]; then
        gconftool-2 -t string -s \
            /apps/metacity/keybinding_commands/edd "$EDD_COMMAND" &&
        gconftool-2 -t string -s \
            /apps/metacity/global_keybindings/run_edd "<Shift><Alt>e"
    # Gnome 3
    else
        # Prepare schema, path and the whole key identification
        schema="org.gnome.settings-daemon.plugins.media-keys"
        path="/org/gnome/settings-daemon/plugins/media-keys/custom-keybindings"
        key="$schema.custom-keybinding:$path/edd/"

        # Need to append the new key to custom-keybindings list
        keys=$(gsettings get $schema custom-keybindings)
        keys=$(echo $keys | sed "s:\]:, '$path/edd/']:")
        keys=$(echo $keys | sed "s:^\[, :[:")

        # Perform the setting
        gsettings set $key "name" "Edd" &&
        gsettings set $key "binding" "<Shift><Alt>e" &&
        gsettings set $key "command" "$EDD_COMMAND" &&
        gsettings set $schema "custom-keybindings" "$keys"
    fi
    if [ $? -eq 0 ]; then
        echo "Shortcut successfully set up"
        exit 0
    else
        echo "Problem with setting up the shortcut"
        exit 1
    fi
}

# Detect the default text editor
editor() {
    # Nothing to be done if user editor set
    [ -n "$EDITOR" ] && return

    # Check for some most common text editors
    [ -x "/usr/bin/vim" ] && EDITOR=vim && return
    [ -x "/usr/bin/gedit" ] && EDITOR=gedit && return
    [ -x "/usr/bin/vi" ] && EDITOR=vi && return
    [ -x "/usr/bin/nano" ] && EDITOR=nano && return

    # Bail out otherwise
    echo >&2 "Sorry, no suitable text editor detected."
    echo >&2 "Hint: Set \$EDITOR variable to your favorite editor."
    exit 1
}

# Save clipboard content into a new temporary file
save() {
    # Use custom prefix for the temporary file
    # (to find it easily if something goes wrong)
    file=$(mktemp /tmp/edd.XXXXXXX.txt)

    # Save the clipboard (try primary selection first)
    xclip -selection primary -o > $file
    if ! [ -s $file ]; then
        xclip -selection clipboard -o > $file
    fi
}

# Select the last edited file
last() {
    file=$(ls -t /tmp/edd.*.txt | head -1)
}

# Choose from the previously edited files
list() {
    i=0
    for file in `ls -t /tmp/edd.*.txt`; do
        values[$(($i*2))]=$file
        values[$(($i*2+1))]=$(head -n 10 $file)
        i=$(($i+1))
    done
    file=$(zenity --list --column File --column Text \
        --title Edd --text "Choose from previous clipboards" \
        --width 800 --height 600 \
        "${values[@]}")
    # Work around BZ#1060471
    file=$(echo "$file" | sed 's/|.*//')
    # Bail out if no file selected
    [ -z "$file" ] && exit 0
}

# Edit the clipboard
edit() {
    # Edit content
    $EDITOR "$file"

    # Read the clipboard
    # (nohup necessary to serve the content if window closed)
    awk 'NR>1{print PREV} {PREV=$0} END{printf("%s",$0)}' "${file}" \
        | nohup xclip -selection clipboard -i &>/dev/null
}

# Decide what to do
if [ "$1" == "--help" -o "$1" == "-h" ]; then
    usage
elif [ "$1" == "--shortcut" ]; then
    # Detect gnome version
    if rpm -q gnome-desktop3 &>/dev/null; then
        gnome="3"
    elif rpm -q gnome-desktop 2>/dev/null | grep -q gnome-desktop-2; then
        gnome="2"
    else
        echo "Unable to detect gnome version, shortcut not set, exiting."
        exit 1
    fi
    # Set up the shortcuts
    shortcut $gnome
else
    # Detect file to edit or save clipboard content
    if [ "$1" == "--list" ]; then
        list
    elif [ "$1" == "--last" ]; then
        last
    else
        save
    fi
    # Detect editor and finally edit
    editor
    edit
fi
