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

mkdir -vp /dev/shm/logs

set logs (journalctl --user -e -n 99999 \
        -u download@\* \
        -u instagram@\* \
        --no-pager \
        | string replace -r \
        "(^.*)(workstation download\[\d+\]\: )" "" \
        | grep -F \[error\] -B 1)

for i in (seq 1 (count $logs))
    set -l log $logs[$i]
    if test (string match -r "\[error\]" $log)
        if test (string match -r \
                "NotFoundError\: Twitter suspends accounts" \
                $log)
            set -a filter_suspended $i
        else if test (string match -r \
                "Tweets are protected" $log)
            set -a filter_protected $i
        else if test (string match -r \
                "Requested user could not be found" $log)
            set -a filter_missing $i
        else if test (string match -r \
                "\[instagram\]\[error\] HttpError\: \'404 Not Found\'" $log)
            set -a filter_missing $i
        else if test (string match -r \
                "Unable to retrieve Tweets from this timeline" $log)
            set -a filter_empty $i
        else
            set -a filter_others $i
        end
    end
end

function _print_accounts -a filter_name --inherit-variable logs
    set i_list $argv[3..-1]
    for i in $i_list
        set regex "\[\d+\/\d+\] "
        set log $logs[(math $i-1)]
        if test (string match -r $regex $log)
            string replace -r $regex "" $log >>/dev/shm/logs/$filter_name
        end
    end
    if test -e /dev/shm/logs/$filter_name
        echo "The following accounts are $filter_name:"
        for line in (cat /dev/shm/logs/$filter_name | sort | uniq)
            echo "- " $line
        end
        echo ""
    end
end

_print_accounts suspended $filter_suspended
_print_accounts protected $filter_protected
_print_accounts missing $filter_missing
_print_accounts empty $filter_empty

echo "The following accouns have other errors:"
for i in $filter_others
    echo $logs[(math $i-1)]
    echo $logs[$i]
end

command rm -rf /dev/shm/logs
