#!/usr/bin/env bash

print_help() {
    (>&2 cat <<EOF
Modify the database of installed binaries.
Usage: $0 -h|-?|--help
           Print this help text and exit.
     - $0 exists <package-name>
           Check whether the package has been installed. The exit code
           is set to 0 if the package exists, and 1 otherwise.
     - $0 reg(ister) <package-name> <file containing the list of files the package owns>
           Add the package to the list of registered packages.
           Use \`sspt add\` to actually install the package.
     - $0 unreg(ister) <package-name>
           Remove the package from the list of registered packages.
NOTE: this subcommand is supposed to be used only by ssbt internally.
      Proceed with caution.
EOF
)
}

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

    case $1 in
        -h|-?|--help)
            print_help
            ;;
        exists)
            if [ $# -lt 2 ]; then   print_help; exit 1; fi
            egrep -q -e "^$ESCAPED_PKG " -f "$SSPT_BIN_DB_FILE"
            return $?
            ;;
        reg|register)
            if [ $# -lt 3 ]; then   print_help; exit 1; fi
            if ! [ -f "$3" ]; then  print_help; exit 1; fi

            # check whether package exists
            egrep -q -e "^$ESCAPED_PKG " -f "$SSPT_BIN_DB_FILE"
            if [ $? -ne 0 ]; then
                # doesn't exist
                echo "$2" >> "$SSPT_BIN_DB_FILE"
                cp "$3" "$SSPT_BIN_DB_DIR/$ESCAPED_PKG"
            else
                # update path
                (>&2 echo "WARNING: This package is already registered, updating its path...")
                local TMPFILE="$(temp_filename)"
                egrep -v -e "^$ESCAPED_PKG " -f "$SSPT_BIN_DB_FILE" > "$TMPFILE"
                echo "$2" >> "$TMPFILE"
                mv "$TMPFILE" "$SSPT_BIN_DB_FILE"
                cp "$3" "$SSPT_BIN_DB_DIR/$ESCAPED_PKG"
            fi
            ;;
        unreg|unregister)
            if [ $# -lt 2 ]; then   print_help; exit 1; fi

            egrep -q -e "^$ESCAPED_PKG " -f "$SSPT_BIN_DB_FILE"
            if [ $? -eq 0 ]; then
                # exists
                local TMPFILE="$(temp_filename)"
                egrep -v -e "^$ESCAPED_PKG" -f "$SSPT_BIN_DB_FILE" > "$TMPFILE"
                mv "$TMPFILE" "$SSPT_BIN_DB_FILE"
                rm "$SSPT_BIN_DB_DIR/$ESCAPED_PKG"
            else
                (>&2 echo "Package doesn't exist.")
            fi
            ;;
    esac
}

main $@

