#!/bin/bash

# Setup to ignore certain files from git.
#
# Preparations:
#    - git clone https://github.com/endeavouros-team/PKGBUILDS.git
#    - cd PKGBUILDS/eos-pkgbuild-setup
#
# We want to add/update files:
#    - PKGBUILDS/.gitignore
#    - ~/.config/git/ignore

DIE() {
    echo "Error: $1" >&2
    exit 1
}

AddGitIgnores() {
    local file="$1"
    local ignoredef count=0
    shift

    for ignoredef in "$@" ; do
        if [ -z "$(grep "^$ignoredef$" "$file")" ] ; then
            echo "$ignoredef" >> "$file"
            ((count++))
        fi
    done
    [ $count -gt 0 ] && echo "Updated $file"
}

Main() {
    local workdir=eos-pkgbuild-setup
    local file
    local xx count
    local ignores=()

    # Check the working folder.

    case "$PWD" in
        */PKGBUILDS/$workdir) workdir="$PWD" ;;
        *) DIE "Run this in folder <path>/PKGBUILDS/$workdir" ;;
    esac

    # Set up PKGBUILDS/.gitignore.

    local pkgdef="*$(grep '^PKGEXT=' /etc/makepkg.conf 2>/dev/null | cut -d '=' -f2 | tr -d "'")"
    ignores=(
        "$pkgdef"             # package files to ignore, like "*.pkg.tar.zst"
        "*~"                  # emacs backup files
        pkg                   # makepkg leftover
        src                   # makepkg leftover
        REGTEST               # ad hoc stuff (optional)
    )
    AddGitIgnores "$workdir/../.gitignore" "${ignores[@]}"

    # Set up "global" git ignores.

    ignores=(
        ".gitignore"          # version control not needed for these files
        ".no-cd"              # used by package cd-path (optional)
        ".GitUpdate"          # used by app EosGitUpdate
        EXPERIMENTAL          # ad hoc stuff (optional)
        TODO                  # ditto
        RCS                   # ditto
    )
    AddGitIgnores "$HOME/.config/git/ignore" "${ignores[@]}"
}

Main "$@"
