#!/usr/bin/env bash

# universal/common-dependencies hash: {{ include (joinPath ".chezmoitemplates" "universal" "common-dependencies") | sha256sum }}
# centos/common-dependencies hash: {{ include (joinPath ".chezmoitemplates" "centos" "common-dependencies") | sha256sum }}

{{ includeTemplate "universal/logg-before" }}

{{- $packages := splitList " " (includeTemplate "universal/common-dependencies" .) -}}
{{- $additionalPackages := splitList " " (includeTemplate "centos/common-dependencies" .) -}}
{{- $packages = concat $packages $additionalPackages -}}

### Detect package manager
if command -v dnf > /dev/null; then
    PKG_MANAGER='dnf'
else
    PKG_MANAGER='yum'
fi

### Print dependency list
logg 'Installing common dependencies using `'"$PKG_MANAGER"'`'
logg info 'Dependencies: {{ $packages | sortAlpha | uniq | join " " -}}'

### Install packages if they are not already present
for PACKAGE in {{ $packages | sortAlpha | uniq | join " " -}}; do
    logg info 'Checking for presence of `'"$PACKAGE"'`'
    if rpm -qa | grep "^$PACKAGE-" > /dev/null; then
        logg info 'The '"$PACKAGE"' package is already installed'
    else
        logg info 'Installing `'"$PACKAGE"'`'
        sudo "$PKG_MANAGER" install -y "$PACKAGE" || EXIT_CODE=$?
        if [ -n "$EXIT_CODE" ]; then
            logg error 'Error installing `'"$PACKAGE"'` via `'"$PKG_MANAGER"'`'
            logg info 'Proceeding with installation..'
            unset EXIT_CODE
        fi
    fi
done
