#!/bin/bash
VERSION="0.1"
DESCRIPTION="Command/Subcommand line script template"

usage() {
  echo "Usage: $0 (install|add_repo) args" 1>&2; exit 1;
}
function disable_repos {
  # Disable all repos
  for repo in "${repos[@]}"; do
    zypper modifyrepo -d $repo
  done

  # Add OBS repository
  zypper ar $OBS_REPOSITORY_URL obs_repository
}

function enable_repos {
  # Remove our obs repository
  zypper rr obs_repository

  # Enable all repos
  for repo in "${repos[@]}"; do
    zypper modifyrepo -e $repo
  done
}

install() {
  shift # remove the subcommand

  # Get enables repos and store them so we can enable them in the end.
  readarray -t repos <<< "$(zypper ls -E | grep "Yes" | awk '{print $1}' )"

  [ ! -z "$OBS_REPOSITORY_URL" ] && disable_repos

  zypper ref
  # TODO: use the "-r" option to avoid disabling/enabling repos
  zypper --no-gpg-checks -n in "$@"

  [ ! -z "$OBS_REPOSITORY_URL" ] && enable_repos
}

# Currently only this format is supported:
# obs_pkg_mgr add_repo <URI> <alias>
# obs_pkg_mgr add_repo <URI> <alias>
add_repo() {
  shift # remove the subcommand

  # No need to refresh the repo if we are inside OBS
  if [ ! -z "$OBS_REPOSITORY_URL" ]; then
    zypper ar -C -G "$@"
  else
    zypper ar -G "$@"
  fi
}

case "$1" in
  install)
    install "$@"
    ;;
  add_repo)
    add_repo "$@"
    ;;
  *)
    usage
    exit 1
    ;;
esac

exit 0;
