#!/usr/bin/env bash

print_help() {
    (>&2 cat <<EOF
Modify the database of pulled source code.
Usage: $0 -h|-?|--help
           Print this help text and exit.
     - $0 exists <package-name>
           Check whether the package has been pulled. The exit code
           is set to 0 if the package exists, and 1 otherwise.
     - $0 reg(ister) <package-name> <current commit id>
           Add the package to the list of registered packages.
           Use \`sspt pull\` to actually download 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=
    if ! [ -z "$2" ]; then
        ESCAPED_PKG=`escape_string $2`
    fi

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

            # check whether package exists
            egrep -q -e "^$ESCAPED_PKG " -f "$SSPT_SRC_DB_FILE"
            if [ $? -ne 0 ]; then
                echo "$2 $3" >> "$SSPT_SRC_DB_FILE"
            else
                # update path
                (>&2 echo "WARNING: Package '$2' is already registered, updating its path...")
                local TMPFILE="$(temp_filename)"
                # grep can bork when the intput and output files are the same
                egrep -v -e "^$ESCAPED_PKG " -f "$SSPT_SRC_DB_FILE" > "$TMPFILE"
                echo "$2 $3" >> "$TMPFILE"
                mv "$TMPFILE" "$SSPT_SRC_DB_FILE"
            fi
            ;;
        unreg|unregister)
            if [ $# -lt 2 ]; then   print_help; exit 1; fi

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

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

touch "$SSPT_SRC_DB_FILE"
main $@
exit $?

