#!/usr/bin/env bash

print_help() {
    (>&2 cat <<EOF
Purge a package without deleting the installed binaries.
Usage: $0 [-h|-?|--help]
           Print this help text and exit.
     - $0 <package-name>
           Orphanize the package.
EOF
)
}

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

    if [ -z "$2" ]; then
        print_help
        exit
    fi

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

            # 1. unreg in the bin db
            exec_subcommand bin-db exists "$1"
            if [ $? -eq 0 ]; then
                exec_subcommand bin-db unreg "$1"
            else
                (>&2 echo "This package isn't installed.")
                exit 1
            fi

            # 2. unregister
            exec_subcommand src-db unreg "$1"

            # 3. nuke
            rm -rf "$SSPT_DL_DIR/$ESCAPED_PKG"
            ;;
    esac
}

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

main $@

