#! /usr/bin/env nix-shell
#! nix-shell -i bash -p bash fd borgbackup gum ripgrep

BORG_PASSPHRASE=$(gum input --password --placeholder "Type borg password")
export BORG_PASSPHRASE

d_root=$HOME/pika
f_string=home/jawz/.config/jawz/lists/jawz/watch.txt
d_borg=/srv/pool/backups/pika/lists

while IFS= read -r repo; do
    IFS=" " read -r -a array <<<"$repo"
    repo_id="${array[0]}"
    mkdir -vp "$d_root/$repo_id" && cd "$d_root/$repo_id" || exit
    borg extract $d_borg::"$repo_id" $f_string
    cat "$d_root/$repo_id/$f_string" >>"$d_root/master"
done < <(borg list "$d_borg")

cd "$HOME" || exit

sort -u "$d_root/master" -o "$d_root/sorted"
sort -u "$LW" -o "$LW"

echo "Current $(wc -l <"$LW") archived $(wc -l <"$d_root/sorted")"

echo "Missing lines:"
diff "$d_root/sorted" "$LW"

# look for duped lines with different casing
echo "Duplicated lines:"
while IFS= read -r line; do
    if ! [ "$line" == "${line,,}" ]; then
        if rg "${line,,}" <"$LW"; then
            echo "$line"
        fi
    fi
done <"$LW"

# delete pika backups
if gum confirm "Limpiar pika?"; then
    command rm -rf "$d_root"
    while IFS= read -r repo; do
        IFS=" " read -r -a array <<<"$repo"
        repo_id="${array[0]}"
        gum spin --spinner dot --title "Cleaning $repo_id..." -- borg delete $d_borg::"$repo_id"
    done < <(borg list "$d_borg")
else
    echo "Canceled, no files deleted"
fi
gum spin --spinner dot --title "Cleaning $repo_id..." -- borg compact "$d_borg"
gum spin --spinner dot --title "Cleaning $repo_id..." -- borg compact /srv/pool/backups/pika/home
