#!/bin/bash

REPO="/data/github/active/Melawy/REPO/melawy/x86_64/"

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

CWD=$(cat pwd.txt)

dir_list=$(find . -mindepth 2 -maxdepth 4 -name "PKGBUILD" -type f)

for i in ${dir_list[@]}
do
    path="$(dirname $i)"
    full_path="$CWD/$path"

    echo "$full_path"
    cd "$full_path"

    git_dir="$(find . -mindepth 1 -maxdepth 1 -name "$(basename $full_path)" -type d)"
    if [ -n "$git_dir" ] && [ -d "$git_dir" ]; then
        echo "rm -rf $git_dir"
        rm -rf "$git_dir"
    fi

    if [ -d "$full_path/src" ]; then
        rm -rf "$full_path/src"
    fi

    if [ -d "$full_path/pkg" ]; then
        rm -rf "$full_path/pkg"
    fi

    make_file=$(find . -mindepth 1 -maxdepth 1 -name "*make*\.sh" -type f)
    if [ -f "$make_file" ]; then
        echo "bash $make_file"
        bash "$make_file"
    else
        makepkg --syncdeps --asdeps --needed --noconfirm --clean --cleanbuild --force

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

    pkg_file=$(find . -mindepth 1 -maxdepth 1 -name "*.pkg.tar.*" -type f)
    sig_file="${pkg_file}.sig"

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

    if [ -n "$git_dir" ] && [ -d "$git_dir" ]; then
        echo "rm -rf $git_dir"
        rm -rf "$git_dir"
    fi

    if [ -d "$full_path/src" ]; then
        rm -rf "$full_path/src"
    fi

    if [ -d "$full_path/pkg" ]; then
        rm -rf "$full_path/pkg"
    fi

    cd "$CWD"
done

notify-send -a "$(basename $(pwd)): Make and Move to" -t 10000 "$REPO" "$(date '+%Y.%m.%d %H:%M:%S')"

echo "Ready"
