#! /bin/bash

readonly SOURCE_LIST_FILENAME=toptracker.list
readonly REPOCONFIG="deb http://tracker-api.toptal.com/desktop/updates/ debian/"

APT_CONFIG="`which apt-config 2> /dev/null`"

# Parse apt configuration and return requested variable value.
apt_config_val() {
    APTVAR="$1"
    if [ -x "$APT_CONFIG" ]; then
        "$APT_CONFIG" dump | sed -e "/^$APTVAR /"'!d' -e "s/^$APTVAR \"\(.*\)\".*/\1/"
    fi
}

# Set variables for the locations of the apt sources lists.
find_apt_sources() {
    APTDIR=$(apt_config_val Dir)
    APTETC=$(apt_config_val 'Dir::Etc')
    APT_SOURCES=$(realpath "$APTDIR/$APTETC$(apt_config_val 'Dir::Etc::sourcelist')")
    APT_SOURCESDIR=$(realpath "$APTDIR/$APTETC$(apt_config_val 'Dir::Etc::sourceparts')")
}

# Add the TopTracker repository to the apt sources.
# Returns:
# 0 - no update necessary
# 1 - sources were updated
# 2 - error
update_sources_lists() {
    find_apt_sources

    if [ -d "$APT_SOURCESDIR" ]; then
      # Nothing to do if it's already there.
      SOURCELIST=$(grep -H "$REPOCONFIG" "$APT_SOURCESDIR/$SOURCE_LIST_FILENAME" \
          2>/dev/null | cut -d ':' -f 1)
      if [ -n "$SOURCELIST" ]; then
          return 0
      fi

      printf "$REPOCONFIG\n" > "$APT_SOURCESDIR/$SOURCE_LIST_FILENAME"
      if [ $? -eq 0 ]; then
          return 1
      fi
    fi
    return 2
}

update_sources_lists
exit 0
