variables:
  GITLAB_CI_IMAGE_DEBIAN: 'debian:buster'
  GITLAB_CI_APT_REPOSITORY: 'deb http://download.opensuse.org/repositories/home:/librespace:/satnogs/Debian_10/ /'
  GITLAB_CI_APT_KEY_URL: 'https://download.opensuse.org/repositories/home:librespace:satnogs/Debian_10/Release.key'
  GITLAB_CI_OBS_PROJECT: 'home:librespace:satnogs'
  GITLAB_CI_OBS_PROJECT_UNSTABLE: 'home:librespace:satnogs-unstable'
stages:
  - build
  - deploy
debian:
  stage: build
  image: ${GITLAB_CI_IMAGE_DEBIAN}
  before_script:
    - apt-get -q update
    - apt-get -qy install gnupg libcurl4 git
    - echo "$GITLAB_CI_APT_REPOSITORY" > /etc/apt/sources.list.d/${GITLAB_CI_OBS_PROJECT}.list
    - apt-key adv --fetch-keys "$GITLAB_CI_APT_KEY_URL"
    - apt-get -q update
    - apt-get -qy install devscripts git-buildpackage
  script:
    - mk-build-deps -i -r -t "apt-get -o Debug::pkgProblemResolver=yes --no-install-recommends -y"
    - PACKAGE_VERSION="$CI_COMMIT_TAG"
    - PACKAGE_VERSION="${PACKAGE_VERSION:-$(git describe --abbrev=8 2>/dev/null | tr '-' '+' || true)}"
    - |
      [ -z "$PACKAGE_VERSION" ] || {
          dch -b -M -v "${PACKAGE_VERSION}-1" "Bump to version '${PACKAGE_VERSION}-1'"
          dch -r -m ""
      }
    - gbp buildpackage -us -uc --git-upstream-tag='HEAD' --git-ignore-branch --git-ignore-new
    - mkdir artifacts
    - cp -a ../*.{deb,diff.gz,dsc,build,buildinfo,changes,orig.tar.gz} artifacts/
  artifacts:
    expire_in: 1 week
    when: always
    paths:
      - artifacts
deploy:
  stage: deploy
  image: ${GITLAB_CI_IMAGE_DEBIAN}
  before_script:
    - apt-get -q update
    - apt-get -qy install osc
  script:
    - |
      cat <<-EOF > ~/.oscrc
      [general]
      apiurl = https://api.opensuse.org
      [https://api.opensuse.org]
      user = $OBS_USER
      pass = $OBS_PASS
      EOF
    - |
      BASE_DIR="$(pwd)"
      OSC_WORKDIR="$BASE_DIR/osc_workdir"
      ARTIFACTS_DIR="$BASE_DIR/artifacts"
      DSC_FILENAME=$(basename $(ls "$ARTIFACTS_DIR"/*.dsc))
      PACKAGES="${DSC_FILENAME%%_*}${CI_COMMIT_TAG:+ ${DSC_FILENAME%.dsc}}"
      PROJECTS="${GITLAB_CI_OBS_PROJECT_UNSTABLE}${CI_COMMIT_TAG:+ ${GITLAB_CI_OBS_PROJECT}}"
      for package in $PACKAGES; do
          for project in $PROJECTS; do
              mkdir -p "$OSC_WORKDIR"
              cd "$OSC_WORKDIR"
              [ -d "$project" ] || osc co "$project"
              cd "$project"
              [ -d "$package" ] || osc mkpac "$package"
              rm -f "$package"/*.{dsc,diff.gz,orig.tar.gz}
              cp -a "$ARTIFACTS_DIR"/*.{dsc,diff.gz,orig.tar.gz} "$package"
              osc addremove -r
              osc ci -m "$DSC_FILENAME"
              cd "$BASE_DIR"
              rm -r "$OSC_WORKDIR"
          done
      done
  only:
    refs:
      - master
      - tags
    variables:
      - $OBS_USER
      - $OBS_PASS
