#!/bin/bash
SOURCE="$0"
source /usr/lib/elive-tools/functions
EL_REPORTS="1"
el_make_environment
. gettext.sh
TEXTDOMAIN="elive-news"
export TEXTDOMAIN

# Lock system {{{
lockfile="/tmp/.$(basename $0)-${USER}.lock"
#set -x

exit_ok(){
    rm -f "$lockfile"
}
exit_error(){
    rm -f "$lockfile"
}

if ps ux | grep -v grep | grep -qs "yad.*notification.*-x-news" ; then
    el_debug "$SOURCE using yad widget already running, exiting..."
    exit
fi

if [[ -r "$lockfile" ]] ; then
    PROCCESS="$(cat $lockfile)"
else
    PROCCESS=" "
fi
if (ps up $PROCCESS) 1>/dev/null 2>&1 ; then
    # el_error "$(basename $0) already running"
    # exit
    kill $PROCCESS
fi

# traps needs to be after the lock verification, in order to not remove it when we are already running
trap "exit_ok" EXIT
trap "exit_error" 1 3 5 6 14 ERR

# SET the lock file
echo "$$" > "$lockfile"


# end lock system }}}

convert_dehtml(){
    local buf
    buf="$( echo "$@" | perl -MHTML::Entities -pe 'decode_entities($_);' 2>/dev/null )"
    if [[ -n "$buf" ]] ; then
        echo "$buf"
    else
        echo "$@"
    fi
}

main(){
    # pre {{{
    local feed_elive_news feed_forum_annoucements line title link category menu_news conf arg version_last_released_stable version_last_released_beta

    # never run on live mode
    if grep -qs "boot=live" /proc/cmdline ; then
        exit
    fi

    # this link is only for releases:
    # this link includes all the updates in elive pages (releases, news, posts published, etc...)
    #feed_elive_news="https://www.elivecd.org/feed/"
    #feed_elive_news="https://feeds.feedburner.com/EliveLinuxWebsiteUpdates"
    feed_elive_news="https://feeds.feedburner.com/elivecd/IQfT"
    # feed_forum_annoucements="https://forum.elivelinux.org/c/announcements/features/18.rss"
    feed_forum_annoucements="https://forum.elivelinux.org/c/announcements/43.rss"
    news_history="$HOME/.cache/$(basename $0)/news-history.txt"
    # history's should be based in the news feed to catch, in order to avoid mixed states

    if ! [[ -e "$news_history" ]] ; then
        mkdir -p "$( dirname "$news_history" )"
    fi
    #curl -L "$feed_forum_annoucements" > "/tmp/feed_forum_annoucements.xml" # tests/debug
    #curl -L "$feed_elive_news" > "/tmp/feed_elive_news.xml" # tests/debug
    #exit

    # do not run in the same user's session: update: not tested - no needed, if this is run only when destkop starts, which is more or less the same
    #if el_flag check "elive-news" ; then
        #exit
    #fi
    #el_flag add "elive-news"

    # }}}

    for arg in "$@"
    do
        case "$arg" in
            --delayed)
                is_delayed=1
                shift
                ;;
        esac
    done

    if ((is_delayed)) ; then
        el_debug "delayed 20 seconds"
        sleep 20
    fi


    el_config_get


    #
    # show the last elive news
    #
    count=0
    while read -ru 3 line
    do
        # title:  <title>Elive 2.9.26 beta released</title>
        if [[ "$line" = *"<title>"*"</title>"* ]] ; then
            line="${line#*<title>}"
            line="${line%</title>*}"
            # skip invalid ones
            if [[ "$line" = "News"*"Elive Linux" ]] ; then
                continue
            fi
            #el_debug "title: $title"
            line="$( convert_dehtml "$line" )"
            line=${line//!/}
            title="$line"
        fi

        #link:  <link>http://feedproxy.google.com/~r/elivecd/IQfT/~3/pUtohK1YFC8/</link>   # this will redirect and should be the correct link
        if [[ "$line" = *"<link>http"*"</link>"* ]] ; then
            line="http${line#*>http}"
            line="${line%</link>*}"
            #el_debug "link: $link"
            link="$line"
        fi

        # category:  <category><![CDATA[Beta]]></category>
        if [[ "$line" = *"<category>"*"</category>"* ]] ; then
            line="${line#*CDATA[}"
            line="${line%]]>*}"
            line=${line//!/}
            #el_debug "category: $category"
            category="$line"

            # ignore some categories
            if echo "$category" | grep -qsiE "(testimonials)" ; then
                unset link title category
                continue
            fi
        fi

        if [[ "$line" = *"</item>"* ]] && [[ -n "$title" ]] && [[ -n "$link" ]] ; then
            if ! LC_ALL=C grep -Fqs "${title}::${link}::" "$news_history" ; then
                # always write the conf? (will not require the manual Exit)
                el_array_member_add "${category}: ${title}!web-launcher '${link}'!star|" "${menu_news_entry_a[@]}" ; menu_news_entry_a=("${_out[@]}")
                el_array_member_add "${title}::${link}::${category}" "${news_entries_a[@]}" ; news_entries_a=("${_out[@]}")
                el_debug "NEW $title"
            else
                el_debug "OLD $title"
            fi
            #echo "$title"
            #echo "$link"
            #echo "$category"
            count="$(( $count + 1 ))"
            unset title link category
        fi

        # show max news
        if [[ "$count" -ge 8 ]] ; then
            break
        fi

    done 3<<< "$( curl -L -s --user-agent "Mozilla/5.0" "$feed_elive_news" )"
    #done 3<<< "$( cat "/tmp/feed_elive_news.xml")" # test/debug




    #
    # show the last forum announcement
    #
    count=0
    while read -ru 3 line
    do
        # title:  <title>Elive 2.9.26 beta released</title>
        if [[ "$line" = *"<title>"*"</title>"* ]] ; then
            line="${line#*<title>}"
            line="${line%</title>*}"
            # skip invalid ones
            if [[ "$line" = "Elive"*"released" ]] ; then
                continue
            fi
            line=${line//!/}
            line="$( convert_dehtml "$line" )"
            title="${line}"
            #el_debug "  title: $title"
        fi

        #link:  <link>http://feedproxy.google.com/~r/elivecd/IQfT/~3/pUtohK1YFC8/</link>   # this will redirect and should be the correct link
        if [[ "$line" = *"<link>http"*"</link>"* ]] ; then
            line="http${line#*>http}"
            line="${line%</link>*}"
            link="${line}"
            #el_debug "  link: $link"
        fi

        # category:  <category><![CDATA[Beta]]></category>
        if [[ "$line" = *"<category>"*"</category>"* ]] ; then
            line="${line#*<category>}"
            line="${line%</category>*}"
            line="${line#*CDATA[}"
            line="${line%]]>*}"
            line=${line//!/}
            category="${line}"
            #el_debug "  category: $category"

            # ignore some categories
            #if echo "$category" | grep -qsiE "(testimonials)" ; then
                #unset link title category
                #continue
            #fi
        fi

        if [[ "$line" = *"</item>"* ]] && [[ -n "$title" ]] && [[ -n "$link" ]] ; then
            #if ! LC_ALL=C grep -qs "^${title}::${link}::" "$news_history" ; then
            if ! LC_ALL=C grep -Fqs "${title}::${link}::" "$news_history" ; then
                # always write the conf? (will not require the manual Exit)
                #echo "${title}::${link}::${category}" >> "$news_history"
                case "$category" in
                    "Features")       icon="gwget" ; ;;
                    "Designs")        icon="preferences-desktop-theme" ; ;;
                    #*)                icon="dialog-information" ; ;;
                    *)                icon="config-users" ; ;;
                esac
                el_array_member_add "${category}: ${title}!web-launcher '${link}'!${icon}|" "${menu_news_entry_a[@]}" ; menu_news_entry_a=("${_out[@]}")
                el_array_member_add "${title}::${link}::${category}" "${news_entries_a[@]}" ; news_entries_a=("${_out[@]}")
                el_debug "NEW $title"
            else
                el_debug "OLD $title"
            fi
            #echo "$title"
            #echo "$link"
            #echo "$category"
            count="$(( $count + 1 ))"
            unset title link category
        fi

        # show max news
        if [[ "$count" -ge 8 ]] ; then
            break
        fi

    done 3<<< "$( curl -L -s --user-agent "Mozilla/5.0" "$feed_forum_annoucements" )"
    #done 3<<< "$( cat "/tmp/feed_forum_annoucements.xml")" # test/debug



    #
    # generate menu of news
    #
    menu_news="$( echo "${menu_news_entry_a[@]}" | sed -e 's;| ;|;g' )"
    read -r menu_news <<< "$menu_news"

    #if yad --notification --command="ls" --menu="${menu_news_entry_a[@]}Exit!quit!cancel" --image=news-icon ; then
    if [[ -n "$menu_news" ]] ; then
        local message_exit message_check_news
        message_exit="$( printf "$( eval_gettext "Close window" )" "" )"
        message_check_news="$( printf "$( eval_gettext "Stay updated with Elive news in the systray. Right-click to close." )" "" )"

        if ! [[ -s "$news_history" ]] ; then
            for line in "${news_entries_a[@]}"
            do
                echo "$line" >> "$news_history"
            done
        else
            # tell the user first
            #notify-send -t 50000 -i text-x-news "Elive News" "$message_check_news"
            el_notify normal "text-x-news" "$( eval_gettext "Elive News" )" "$message_check_news"

            el_debug "yad --notification --command=\"web-launcher 'https://forum.elivelinux.org/t/news-automated-showing-in-your-elive-system/3314'\" --menu=\"${menu_news}${message_exit}!quit!cancel\" --image=text-x-news"

            # NOTE: do not change the icon image unless you change it in the checker too (search in the rest of the code for the same name)
            if yad --notification --command="web-launcher 'https://forum.elivelinux.org/t/news-automated-showing-in-your-elive-system/3314'" --menu="${menu_news}${message_exit}!quit!cancel" --image=text-x-news ; then
                # write the conf only if the user has clicked to Exit, otherwise will appear again in the next session
                for line in "${news_entries_a[@]}"
                do
                    echo "$line" >> "$news_history"
                done
            fi

        fi

        is_news_given=1
    fi





    # show a simple popup about the last versions released:
    # beta
    if ((is_delayed)) ; then
        sleep 10
    fi
    version_last_released_beta="$( lynx -dump https://www.elivecd.org/download/beta/ | grep -iE "^Elive [[:digit:]]+\.[[:digit:]]+\.[[:digit:]]+ Beta$" | awk '{print $2}' )"
    if [[ -n "$version_last_released_beta" ]] ; then
        if [[ -n "$conf_version_last_released_beta" ]] ; then
            if dpkg --compare-versions "$conf_version_last_released_beta" lt "$version_last_released_beta" ; then

                if ! ((is_news_given)) ; then
                    el_notify normal text-x-news "$( eval_gettext "Elive Beta release" ) - ${version_last_released_beta}" "$( eval_gettext "A new beta version of Elive has been published. Visit the website for more information." )"
                    #el_notify normal software-update-available "$( eval_gettext "Elive Beta release" ) - ${version_last_released_beta}" "$( eval_gettext "A new version of Elive Beta has been released. Check the website to know more." )"
                fi
            fi
        fi
        # remember the last version fetched
        conf_version_last_released_beta="$version_last_released_beta"
        el_config_save "conf_version_last_released_beta"
    else
        el_debug "unable to know the version of the last beta version of elive"
    fi
    # stable
    if ((is_delayed)) ; then
        sleep 10
    fi
    version_last_released_stable="$( lynx -dump https://www.elivecd.org/download/stable/ | grep -iE "^Elive [[:digit:]]+\.[[:digit:]]+\.[[:digit:]]+ Stable$" | awk '{print $2}' )"
    if [[ -n "$version_last_released_stable" ]] ; then
        if [[ -n "$conf_version_last_released_stable" ]] ; then
            if dpkg --compare-versions "$conf_version_last_released_stable" lt "$version_last_released_stable" ; then

                if ! ((is_news_given)) ; then
                    #el_notify normal text-x-news "$( eval_gettext "Elive stable release" ) - ${version_last_released_stable}" "$( eval_gettext "A new stable version of Elive has been released! Visit the website to learn more." )"
                    el_notify normal software-update-available "$( eval_gettext "Elive Stable release" ) - ${version_last_released_stable}" "$( eval_gettext "A new stable version of Elive has been released! Visit the website to learn more." )"
                fi
            fi
        fi
        # remember the last version fetched
        conf_version_last_released_stable="$version_last_released_stable"
        el_config_save "conf_version_last_released_stable"
    else
        el_debug "unable to know the version of the last stable version of elive"
    fi




    #
    # Show the Patreon donnors
    #
    local message_patreon_new_donnor_title message_patreon_new_donnor_body message_patreon_new_donnor_footer message_patreon_new_donnor_join
    source /etc/elive/settings 2>/dev/null || true

    patreon_curl="$( curl -m 20 -Ls --user-agent "Mozilla 5.0"  "https://www.patreon.com/elive/about" | grep -E "(patron_count|pledge_sum)" | tr '"' "'" | tr ',' '\n' )"
    if [[ -z "$patreon_curl" ]] ; then
        sleep 2m
        patreon_curl="$( curl -m 20 -Ls --user-agent "Mozilla 5.0"  "https://www.patreon.com/elive/about" | grep -E "(patron_count|pledge_sum)" | tr '"' "'" | tr ',' '\n' )"
    fi
    patreon_currency="$( echo "$patreon_curl" | grep "'pledge_sum_currency':" | sed -e "s|^.*':||g" -e "s|,$||g" -e "s|'||g" )"
    read -r patreon_currency <<< "$patreon_currency"

    if [[ -n "$patreon_curl" ]] ; then
        if [[ -n "$patreon_currency" ]] ; then
            patreon_patrons="$( echo "$patreon_curl" | grep "'paid_member_count':" | sed -e "s|^.*':||g" -e "s|,$||g" | sort -V | tail -n 1 )"
            read -r patreon_patrons <<< "$patreon_patrons"
            patreon_pledge="$( echo "$patreon_curl" | grep "'pledge_sum':" | sed -e "s|^.*':||g" -e "s|,$||g" | sort -V | tail -n 1 )"
            read -r patreon_pledge <<< "$patreon_pledge"
            # remove the two last numbers (decimals)
            patreon_pledge="${patreon_pledge::-2}"
            if [[ -z "$patreon_pledge" ]] || [[ -z "$patreon_patrons" ]] ; then
                el_error "wrong data obtained from patreon curl: $patreon_pledge - $patreon_patrons - $patreon_currency"
            fi

            if ((is_premium_user)) ; then
                message_patreon_new_donnor_title="$( printf "$( eval_gettext "Another user joined Patreon!" )" "" )"
                message_patreon_new_donnor_body="$( printf "$( eval_gettext "With %s supporters, Elive receives a total of %s %s in monthly support!" )" "$patreon_patrons" "$patreon_pledge" "$patreon_currency" )"
                message_patreon_new_donnor_footer="$( printf "$( eval_gettext "Great news! More Patreon supporters mean Elive can progress faster!" )" "" )"
                message_patreon_new_donnor_join="$( printf "$( eval_gettext "Check them out!" )" "" )"
            else
                message_patreon_new_donnor_title="$( printf "$( eval_gettext "A new user has joined the Elive financial support!" )" "" )"
                message_patreon_new_donnor_body="$( printf "$( eval_gettext "With %s supporters, Elive receives a total of %s %s in monthly support!" )" "$patreon_patrons" "$patreon_pledge" "$patreon_currency" )"
                message_patreon_new_donnor_footer="$( printf "$( eval_gettext "Even if you can't contribute much, a small sum is crucial for this project's survival. With your support, Elive can continue to exist." )" "" )"
                message_patreon_new_donnor_join="$( printf "$( eval_gettext "I want to join as well!" )" "" )"
            fi


            if [[ "$patreon_patrons" -gt "$conf_patreon_patrons" ]] ; then
                if ((is_premium_user)) ; then
                    result="$( el_notify wait znes "$message_patreon_new_donnor_title" "${message_patreon_new_donnor_body}\n\n${message_patreon_new_donnor_footer}" )"
                else
                    result="$( el_notify wait znes "$message_patreon_new_donnor_title" "${message_patreon_new_donnor_body}\n\n${message_patreon_new_donnor_footer}"  --action=open="$message_patreon_new_donnor_join" )"
                fi

                if [[ "$result" = "open" ]] ; then
                    web-launcher "https://www.elivecd.org/patreon"
                fi
            fi

            # save to not ask again
            conf_patreon_patrons="$patreon_patrons"
            el_config_save "conf_patreon_patrons"
        else
            el_error "Patreon currency obtained value is not in USD ? '$patreon_currency', $patreon_pledge - $patreon_patrons"
        fi
    fi




    exit_ok

}

#
#  MAIN
#
main "$@"

# vim: set foldmethod=marker :
