#!/bin/bash
# Forwarded to Debian: https://bugs.debian.org/824904
set -e

print_bts_usertags_cmdline () {
	bad="$(basename "$2")"
	good="$1"
	echo -n "bts user $bad , "
	for tag in $(sed -n s/Tag://p "$2") ; do
		for bug in $(sed -n "/^Tag: $tag/,/^$/{1d;p}" "$2" | grep -o '[0-9]*') ; do
			echo -n "usertags $bug - $tag , "
		done
	done
	echo -n "user $good , "
	for tag in $(sed -n s/Tag://p "$2") ; do
		for bug in $(sed -n "/^Tag: $tag/,/^$/{1d;p}" "$2" | grep -o '[0-9]*') ; do
			echo -n "usertags $bug + $tag , "
		done
	done
	echo
}

find_and_correct () {
	local f
	test -d "$1" || return 0
	find "$1/" -type f | while read f ; do
		print_bts_usertags_cmdline "$(basename "$f" | sed "$2")" "$f"
	done
}

download () {
	rsync --timeout=60 rsync://bugs-mirror.debian.org/bts-spool-index/user/*/"$1" "$2/" 2>  >(grep -vE 'No such file or directory|see previous errors' 1>&2) || true
}

dir="$(mktemp --tmpdir --directory debian-usertags-tests-XXXXXXXX)"
cleanup () { rm --recursive --force "$dir"; }
trap cleanup EXIT
cd "$dir"
#download "*" all
# tagsregex=$(ssh buxtehude.debian.org "sed '/^1;$/i print join \"|\", @gTags;' < /srv/bugs.debian.org/etc/config | perl")
#tagsregex="patch|wontfix|moreinfo|unreproducible|fixed|potato|woody|sid|help|security|upstream|pending|sarge|sarge-ignore|experimental|d-i|confirmed|ipv6|lfs|fixed-in-experimental|fixed-upstream|l10n|newcomer|etch|etch-ignore|lenny|lenny-ignore|squeeze|squeeze-ignore|wheezy|wheezy-ignore|jessie|jessie-ignore|stretch|stretch-ignore|buster|buster-ignore|bullseye|bullseye-ignore"
#grep -rE '^Tag: ($tagsregex)$' all || true
download '*.ort' ort
download '*.ogr' ogr
download '*.rog' rog
download '*.debian' debian
download '*packages.qa.debian.org' packages
download '*list.debian.org' list
download '*alioth.debian.org' alioth
download '*.debian.org*bugs.debian.org' qa
find -type f -print0 | xargs -0 rename 's/%40/@/'
find -empty -delete
find_and_correct ort 's/\.ort$/.org/'
find_and_correct ogr 's/\.ogr$/.org/'
find_and_correct rog 's/\.rog$/.org/'
find_and_correct debian 's/\.debian$/&.org/'
find_and_correct debian.com 's/\.debian\.com$/.debian.org/'
find_and_correct debian.net 's/\.debian\.net$/.debian.org/'
find_and_correct packages 's/packages\.qa\.debian\.org$/packages.debian.org/'
find_and_correct list 's/list\.debian\.org$/lists.debian.org/'
find_and_correct qa 's/\.debian\.org@bugs\.debian\.org$/.debian.org@packages.debian.org/'
find_and_correct alioth 's/@alioth\.debian\.org$/@lists.alioth.debian.org/'
