#!/usr/bin/bash

###########################################################################
# Copyright (C) 2020, 2021, 2022 IoT.bzh                                  #
#                                                                         #
# Author:   Salma Raiss <salma.raiss@iot.bzh>                             #
#                                                                         #
# Licensed under the Apache License, Version 2.0 (the "License");         #
# you may not use this file except in compliance with the License.        #
# You may obtain a copy of the License at                                 #
#                                                                         #
#     http://www.apache.org/licenses/LICENSE-2.0                          #
#                                                                         #
# Unless required by applicable law or agreed to in writing, software     #
# distributed under the License is distributed on an "AS IS" BASIS,       #
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.#
# See the License for the specific language governing permissions and     #
# limitations under the License.                                          #
###########################################################################
#                    Get enabled repositories info                        #
###########################################################################

set -e

REPOS_INFO=$(dnf repoinfo)
REPOS_ID=$(echo "$REPOS_INFO" | grep 'Repo-id' | tr -s ' ' |cut -d' ' -f3)
REPOS_BASEURL=$(echo "$REPOS_INFO" | grep 'Repo-baseurl' | tr -s ' ' |cut -d' ' -f3)
REPOS_MIRRORS=$(echo "$REPOS_INFO" | grep 'Repo-mirrors' | tr -s ' ' |cut -d' ' -f3)

repos_count=$(echo "$REPOS_ID" | wc -w)
repos_id=($REPOS_ID)
repos_baseurl=($REPOS_BASEURL)
repos_mirrors=($REPOS_MIRRORS)

if [ -z "${repos_id}" ]; then
    echo enabled repos="No repository is enabled!!!"
    exit 0
fi

repos_info=$(for i in $(seq 0 $repos_count);do
        jq -n --arg pn "${repos_id[$i]}" --arg pv "${repos_baseurl[$i]}" --arg pa "${repos_mirrors[$i]}" \
                '. + {repo_id: $pn, repo_baseurl: $pv, repo_mirrors: $pa}';\
        done | jq -s .)

echo repos_info=${repos_info}
