#!/bin/sh

# Скрипт для обновления ключей для проверки подписей коммитов

if ! git --version > /dev/null 2>&1; then
	printf "\n\033[0;31mGIT is not found!\033[0m\n"; exit 1;
fi

if ! git status > /dev/null 2>&1; then
	printf "\n\033[0;31mThis is not a git repo!\033[0m\n"; exit 1;
fi

domain=$(git remote -v | head -n 1 | tr '\t' ' ' | cut -d ' ' -f2)
domain=$(echo "$domain" | sed 's/.*@//' | sed 's/:.*//')

echo "Repo domain: $domain"

login=$1
password=$2

if [ -z "$login" ]; then
	printf "Enter login: "
	read -r login
fi

if [ -z "$password" ]; then
	stty -echo
	printf "Enter password: "
	read -r password
	stty echo
	printf "\n"
fi

apitest=$(curl -s -u "$login:$password" "https://$domain/api/v1/user")
# echo "apitest: $apitest"

if echo "$apitest" | grep -- 'user does not exist' >/dev/null 2>&1; then
	printf "\033[0;31mERROR: User \"%s\" does not exist on %s\033[0m\n" "$login" "$domain"; exit 1;
fi

if echo "$apitest" | grep -- 'password is invalid' >/dev/null 2>&1; then
	printf "\033[0;31mERROR: Invalid password\033[0m\n"; exit 1;
fi

allowed_signers_file=~/.ssh/allowed_signers

if [ ! -f "$allowed_signers_file" ]; then
	echo "Create $allowed_signers_file"
	touch $allowed_signers_file
fi

users=$(git shortlog -snc --all | tr '\t' ' ' | sed 's/^ *//' | cut -d ' ' -f2)
echo "Repo users: $users" | tr "\n" ' '; echo

echo "" > test.txt
for user in $users; do
	keys=$(curl -s -u "$login:$password" "https://$domain/api/v1/users/$user/keys")
	keys=$(echo "$keys" | tr , '\n' | grep -E -- '^"key":".*' | sed 's/^"key"://' | tr -d '\n')

	IFS='"'
	for key in $keys; do
		if [ "$key" = "" ]; then continue; fi
		if grep -Fq "$key" "$allowed_signers_file"; then continue; fi
		echo "New key for $user"
		printf "%s %s\n" "$user" "$key" >> $allowed_signers_file
	done
	unset IFS
done

echo "$allowed_signers_file updated"