#!/bin/bash

find . -type f -name "*.xz" -delete
find . -type f -name "*.zst" -delete
find . -type f -name "*.sig" -delete

REPO="/data/github/active/Melawy/REPO/melawy-3party/x86_64/"

echo -n $( dirname -- "$( readlink -f -- "$0" )" ) > pwd.txt

CWD=$(cat pwd.txt)

for package_dir in $(find . -mindepth 1 -maxdepth 1 -type d)
do
    cd $CWD/$package_dir

    bash 00_git_pull.sh
    bash 01_patch.sh
    bash 02_make.sh

    for i in *.pkg.tar.zst;
    do
        if [ -f "${i}" ]; then
            echo "Удаление подписи $i.sig"
            rm -f $i.sig
            echo "Добавление подписи $i.sig"
            gpg --detach-sign --local-user BC8B600E8DDA1F4CB77B10D2BA803A261A5EE6B8 --output "$i.sig" "$i"
        fi
    done

    for i in *.pkg.tar.xz;
    do
        if [ -f "${i}" ]; then
            echo "Удаление подписи $i.sig"
            rm -f $i.sig
            echo "Добавление подписи $i.sig"
            gpg --detach-sign --local-user BC8B600E8DDA1F4CB77B10D2BA803A261A5EE6B8 --output "$i.sig" "$i"
        fi
    done

    package_file=$(ls -1 | grep -v "pkg.tar.zst.sig" | grep "pkg.tar.zst" | head -n 1)
    if [ -f "$CWD/$package_dir/$package_file" ]; then
        mv -v $CWD/$package_dir/*.pkg.tar.zst $REPO/
    fi

    package_file=$(ls -1 | grep -v "pkg.tar.xz.sig" | grep "pkg.tar.xz" | head -n 1)
    if [ -f "$CWD/$package_dir/$package_file" ]; then
        mv -v $CWD/$package_dir/*.pkg.tar.xz $REPO/
    fi

    package_file=$(ls -1 | grep "pkg.tar.xz.sig" | head -n 1)
    if [ -f "$CWD/$package_dir/$package_file" ]; then
        mv -v $CWD/$package_dir/*.pkg.tar.xz.sig $REPO/
    fi

    package_file=$(ls -1 | grep "pkg.tar.zst.sig" | head -n 1)
    if [ -f "$CWD/$package_dir/$package_file" ]; then
        mv -v $CWD/$package_dir/*.pkg.tar.zst.sig $REPO/
    fi

    cd $CWD
done

echo "melawy" | beep -f 200 -l 250 -d 100 -r 1 -n -s
notify-send -a "$(basename $(pwd)): Make and Move to" -t 10000 "$REPO" "$(date '+%Y.%m.%d %H:%M:%S')"

echo "Ready"
