#!/usr/bin/env bash

print_help() {
    (>&2 cat <<EOF
Edit the .sspt file of a package.
Usage: $0 [-h|-?|--help]
           Print this help text and exit.
     - $0 <package-name>
           Edit the .sspt file of the package using \$EDITOR.
EOF
)
}

main() {
    local ESCAPED_PKG=`escape_string $1`

    case $1 in
        -h|-?|--help)
            print_help
            ;;
        *)
            exec_subcommand src-db exists "$1"
            if [ $? -ne 0 ]; then
                (>&2 echo "Package '$1' doesn't exist.")
                exit 1
            fi

            local PACKAGE_DIR=$(egrep -e "^$ESCAPED_PKG " -f "$SSPT_SRC_DB_FILE" \
                | egrep -v -o -e "^[A-Za-z0-9_\-\.]* " | egrep -v -o -e " [A-Za-z0-9_\-\.]$")

            command -v "$EDITOR" >/dev/null 2>&1 && "$EDITOR" "$PACKAGE_DIR/.sspt" && return
            command -v "nano" >/dev/null 2>&1 && "nano" "$PACKAGE_DIR/.sspt" && return
            command -v "nvim" >/dev/null 2>&1 && "nvim" "$PACKAGE_DIR/.sspt" && return
            command -v "vim" >/dev/null 2>&1 && "vim" "$PACKAGE_DIR/.sspt" && return
            command -v "vi" >/dev/null 2>&1 && "vi" "$PACKAGE_DIR/.sspt" && return
            ;;
    esac
}

if [ $# -eq 0 ]; then
    print_help
    exit
fi

main $@

