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


ssh_key_check(){
    # delete wrong rsa keys if any (bug from previous version of this script)
    if ! grep -qs "^ssh-rsa " ~/.ssh/id_rsa.pub 2>/dev/null ; then
        rm -f ~/.ssh/id_rsa ~/.ssh/id_rsa.pub
    fi
    # check ssh ID key
    # if [[ ! -s ~/.ssh/id_rsa.pub ]] && [[ ! -s ~/.ssh/id_ed25519.pub ]] && [[ ! -s ~/.ssh/id_ecdsa.pub ]] ; then
    if [[ ! -s ~/.ssh/id_rsa.pub ]] ; then
        el_warning "$( eval_gettext "You don't have an SSH key configured. An SSH key is required and must be added to your Github account to access the Premium features." )"
        if el_confirm "$( eval_gettext "Do you want to create a new SSH key now? (If not, you will need to import your existing SSH keys into:" ) ~/.ssh/id_rsa.pub" ; then
            el_warning "$( eval_gettext "Important: You can optionally skip adding a password for your SSH key. This will prevent you from having to enter it every time you use it. To do so, just press 'Enter' when prompted for a password." )"
            ssh-keygen -t rsa -f ~/.ssh/id_rsa -C "$patreon_email"
        fi
    fi

    # make sure ssh-agent is running and has the key
    if ! ssh-add -l &>/dev/null ; then
        # This will fail with 2 if agent is not running, 1 if agent running but no keys
        if [[ $? -eq 2 ]] ; then
            eval "$(ssh-agent -s)"
        fi

        if [[ -f ~/.ssh/id_rsa ]] ; then
            # Now agent is running for sure.
            # Try to add key silently, might work if no passphrase.
            if ! ssh-add ~/.ssh/id_rsa &>/dev/null ; then
                # It failed, probably needs a passphrase.
                el_info "$(eval_gettext "Please enter the passphrase for your SSH key to add it to the ssh-agent.")"
                if ! ssh-add ~/.ssh/id_rsa < /dev/tty ; then
                    el_warning "$(eval_gettext "Failed to add SSH key to the ssh-agent. Git operations might fail if a passphrase is required.")"
                fi
            fi
        fi
    fi
}

premium_status_get(){
    # get premium status
    patreon_email_checksum="$( echo "$patreon_email" | sha1sum | awk '{print $1}' )"
    if curl -Ls -m 10 -A "Mozilla/5.0" https://www.elivecd.org/files/patreon_members.txt | grep -qs "^${patreon_email_checksum}$" ; then
        is_premium_new=1
    else
        is_premium_new=0
    fi
}

usage(){
    echo
    el_info "$( eval_gettext "Please select one of the following premium features to install:" )"
    echo
    echo "  1) $( eval_gettext "Elivim: An amazing framework for the NeoVim editor." )"
    echo "  2) $( eval_gettext "Elive AI: A collection of handy tools to use Artificial Intelligence on your system." )"
    echo "  3) $( eval_gettext "GPT-UUU: GPT Uncensored, Unbiased, Untracked." )"
    echo "  4) $( eval_gettext "Elive for Servers: Enhancements for your server and more." )"
    echo "  5) $( eval_gettext "Synthwave Player: A music player with a retro-futuristic vibe." )"
    echo
    echo "  0) $( eval_gettext "Exit" )"
    echo

    local choice
    read -p "$( eval_gettext "Enter your choice" ) [0-5]: " choice
    echo

    case "$choice" in
        1) premium_elivim ;;
        2) premium_assistant ;;
        3) premium_gptuuu ;;
        4) premium_servers ;;
        5) premium_synthwave_player ;;
        0) return 0 ;;
        *)
            el_error "$( eval_gettext "Invalid option selected." )"
            return 1
            ;;
    esac
}

github_login_required(){
    el_notify "normal" "logo-elive" "Important" "$( eval_gettext "You need to be logged into Github and have accepted the Elive-Premium invitation to view this page." )"
}

git_github_conf(){
    local username token email

    if [[ -z "$( command git config --get github.user )" ]] ; then
        el_info "$(eval_gettext "Please enter your Github username:")"
        read username
        if [[ -n "$username" ]] ; then
            git config --global github.user "$username"
        else
            el_info "$(eval_gettext "Please enter your Github username:")"
            read username
            if [[ -n "$username" ]] ; then
            git config --global github.user "$username"
            else
                el_error "$(eval_gettext "You must enter your Github username to continue.")"
                exit 1
            fi
        fi
    fi

    if [[ -z "$( command git config --get user.email )" ]] ; then
        if [[ -n "$patreon_email" ]] ; then
            git config --global user.email "$patreon_email"
        else
            el_info "$(eval_gettext "Please enter your email address:")"
            read email
            if [[ -n "$email" ]] ; then
                git config --global user.email "$email"
            else
                read -p "$(eval_gettext "Please enter your email address: ")" email
                if [[ -n "$email" ]] ; then
                    git config --global user.email "$email"
                else
                    el_error "$(eval_gettext "You must enter your email address to continue.")"
                    exit 1
                fi
            fi
        fi
    fi


    # if [[ -z "$( command git config --get github.token )" ]] ; then
    #     el_info "Insert your Github token"
    #     read token
    #     if [[ -n "$token" ]] ; then
    #         git config --global github.token "$token"
    #     else
    #         el_error "You need to insert your Github token in order to continue"
    #         exit 1
    #     fi
    # fi
}

github_access_check(){
    local result is_cloned

    rm -rf "/tmp/${USER}-elivepremium-test.git" || true

    if ! grep -qs "^github.com" ~/.ssh/known_hosts ; then
        ssh-keyscan -t rsa github.com  2>/dev/null  >> ~/.ssh/known_hosts
    fi

    # check github access
    echo -e "Testing access to the Premium Github repositories..." 1>&2

    # fix possible permission issues with .ssh
    chown -R "$USER":"$USER" ~/.ssh
    chmod 700 ~/.ssh
    chmod 600 ~/.ssh/*
    chmod 644 ~/.ssh/*.pub
    chmod o-w ~

    if timeout 20 git clone --quiet git@github.com:Elive-Premium/.github.git "/tmp/${USER}-elivepremium-test.git" ; then
        is_cloned=1
    fi

    rm -rf "/tmp/${USER}-elivepremium-test.git" || true

    if ! ((is_cloned)) ; then
        el_warning "$( eval_gettext "You don't have access to the Elive Premium Github repository. Please add your SSH key to your Github account first." )"
        # el_info "$( eval_gettext "Instructions: You need to add your SSH key to your Github account, you can do it from the following link:" )"

        # copy keys to clipboard
        if cat ~/.ssh/id_rsa.pub 2>/dev/null | xclip -i -selection clipboard ; then
            el_info "$( eval_gettext "Your SSH Public Key has been copied to the clipboard." )"
        else
            el_info "$( eval_gettext "Please copy the contents of your ~/.ssh/id_*.pub file and add it to your Github account." )"
        fi

        el_info "$( eval_gettext "Press Enter to open Github in your browser where you can paste your SSH key." )"
        read nothing
        ( web-launcher "https://github.com/settings/ssh/new" & )

        # copy it again just in case
        for i in $(seq 3) ; do
            sleep 5
            cat ~/.ssh/id_rsa.pub 2>/dev/null | xclip -i -selection clipboard
        done

        sleep 5
        echo
        el_info "$( eval_gettext "Press Enter once you have added your SSH key to Github to continue..." )"
        read nothing
    fi

    if ! ((is_cloned)) ; then
        echo -e "Testing access to the Elive Premium Github repository..." 1>&2
        if ! timeout 20 git clone --quiet git@github.com:Elive-Premium/.github.git "/tmp/${USER}-elivepremium-test.git" ; then
            echo -e "Possible causes:" 1>&2
            echo -e " * You haven't accepted the invitation yet" 1>&2
            echo -e " * Your SSH key is protected by a passphrase that was not prompted for. (Suggestion: create a key without a passphrase by pressing Enter when asked)." 1>&2
            echo -e " * Your github user name must be: '$( git config --get github.user )'" 1>&2
            echo -e " * If you continue to have problems, contact Thanatermesis for assistance." 1>&2
            echo -e " * Your SSH key is not correctly added to your Github account. The key found is:\n\n'$( cat ~/.ssh/id_rsa.pub 2>/dev/null )'" 1>&2
            echo -e "\n\n    * Which should be added to the web page: 'https://github.com/settings/ssh/new'" 1>&2

            el_error "$( eval_gettext "Could not access the Elive Premium Github repository. Please ensure you have received and accepted the invitation. Exiting..." )"
            exit 1
        fi
    fi
}

premium_elivim(){
    # Elivim
    el_info "$( eval_gettext "Elivim: An amazing framework for the NeoVim editor." )"
    if el_confirm "$( eval_gettext "Do you want to install the Elivim framework for Neovim?" )" ; then

        el_dependencies_install "neovim|git|python3-venv|fonts-noto-color-emoji|ripgrep|nodejs|npm|gcc"

        el_info "$( eval_gettext "Please follow the instructions in the terminal." )"

        # github_login_required
        # web-launcher "https://github.com/Elive-Premium/elive-for-servers"

        git clone git@github.com:Elive-Premium/Elivim /tmp/elivim-$$ --depth 1 && /tmp/elivim-$$/elivim --reinstall ; rm -rf /tmp/elivim-$$
    fi
}

premium_assistant(){
    # Assistant
    el_info "$( eval_gettext "Elive AI: A collection of handy tools to use Artificial Intelligence on your system." )"
    if el_confirm "$( eval_gettext "Do you want to install Elive Assistant and its many AI features?" )" ; then
        el_dependencies_install "elive-assistant"
    fi
}

premium_gptuuu(){
    # gptuuu
    el_info "$( eval_gettext "GPT-UUU: GPT Uncensored, Unbiased, Untracked." )"
    if el_confirm "$( eval_gettext "Do you want to install a local AI chat system on your machine?" )" ; then
        el_info "$( eval_gettext "Please follow the instructions in the terminal." )"

        el_dependencies_install "git"
        git clone git@github.com:Elive-Premium/gptuuu /tmp/gptuuu-$$ --depth 1 && /tmp/gptuuu-$$/installer.sh ; rm -rf /tmp/gptuuu-$$
    fi
}

premium_servers(){
    # Servers
    el_info "$( eval_gettext "Elive for Servers: Enhancements for your server and more." )"
    if el_confirm "$( eval_gettext "Do you want to enhance your servers with Elive features? Continue to learn more." )" ; then
        el_info "$( eval_gettext "Check the project website to learn how to use it on your servers." )"
        github_login_required
        web-launcher "https://github.com/Elive-Premium/elive-for-servers"
    fi
}

premium_synthwave_player(){
    # Synthwave Player
    el_info "$( eval_gettext "Synthwave Player: A music player with a retro-futuristic vibe." )"
    if el_confirm "$( eval_gettext "Do you want to install the Synthwave Player?" )" ; then
        el_info "$( eval_gettext "You will be directed to the download page where you must download two .deb files:" )"
        echo "- synthwave-player_..._all.deb"
        echo "- synthwave-player-server_..._all.deb"
        echo
        el_warning "$( eval_gettext "Important: The 'synthwave-player-server' package must be installed only on the machine that will serve the music." )"
        el_info "$( eval_gettext "After downloading, click on the files from your file manager to install them." )"
        echo
        el_info "$( eval_gettext "Press Enter to open the download page." )"
        read nothing
        web-launcher "https://github.com/Elive-Premium/synthwave-player/releases/latest"
    fi
}




main(){
    # pre {{{

    [[ -s /etc/elive/settings ]] && source /etc/elive/settings

    if ! el_dependencies_check "git|curl|wget|ssh-keygen|xclip" ; then
        el_dependencies_install "git|curl|wget|openssh-client|xclip"
    fi

    if ((is_bullseye)) || ((is_buster)) || ((is_wheezy)) ; then
        el_error "$( eval_gettext "This feature is only available for Elive 3.8.40+ (based on Debian Bookworm or newer)." )"
        exit 1
    fi

    is_premium_new=0


    # }}}

    if [[ -n "$patreon_email" ]] ; then
        premium_status_get
    fi

    if ! ((is_premium_new)) ; then
        el_info "$( eval_gettext "To become an Elive Premium user, you need to join Elive's Patreon." )"
        if el_confirm "$( eval_gettext "Would you like to open the website to see the features and benefits of being a Premium user?" )" ; then
            web-launcher "https://www.elivecd.org/premium/"
        fi
        el_info "$( eval_gettext "This user is not yet configured as a Premium user." )"
        if el_confirm "$( eval_gettext "Would you like to open the Patreon website to become a Premium user?" )" ; then
            web-launcher "https://www.patreon.com/elive"
        fi

        local message_email
        message_email="$( printf "$( eval_gettext "Please enter the email address used for your Patreon account or associated with your Premium account." )" "" )"

        el_info "$message_email"
        read -r patreon_email
        patreon_email="$( echo "${patreon_email,,}" )"


        echo "" 1>&2

        premium_status_get
    fi


    # update values
    if [[ "$is_premium_new" != "$is_premium_user" ]] ; then
        el_info "$( eval_gettext "Please enter your administrator password to save the configuration." )"
        gksu bash -c "source /usr/lib/elive-tools/functions ;
        sed -i '/^patreon_email=/d' '/etc/elive/settings' 2>/dev/null || true
        echo 'patreon_email=\"$patreon_email\"' >> /etc/elive/settings
        sed -i '/^is_premium_user=/d' '/etc/elive/settings' 2>/dev/null || true
        echo 'is_premium_user=\"${is_premium_new}\"' >> /etc/elive/settings
        "
    fi
    is_premium_user="$is_premium_new"

    # verify
    if ! ((is_premium_user)) ; then
        el_error "$( eval_gettext "This email address does not belong to a Premium user. Please try the one associated with your Patreon account." )"
        el_info "$( eval_gettext "Instructions: If your Patreon account uses a different email address, you must change it to match what you entered. Note that this email will also be used to access the Github Premium repositories." )"
        exit
    fi

    ssh_key_check
    git_github_conf
    github_access_check

    echo "" 1>&2
    el_info "*** Premium Features ready ***"
    echo "" 1>&2

    case "$1" in
        elivim|neovim)
            premium_elivim
            exit
            ;;
        assistant|ai)
            premium_assistant
            exit
            ;;
        gptuuu|gpt-uuu)
            premium_gptuuu
            exit
            ;;
        servers|server)
            premium_servers
            exit
            ;;
        synthwave|player|"synthwave-player")
            premium_synthwave_player
            exit
            ;;
        *)
            usage
            exit
            ;;
    esac

    # show all of them
    # first run a normal window so that the CSS/JS of the website will load correctly
    web-launcher \
        "https://github.com/Elive-Premium"
        $NULL
    sleep 2

    web-launcher \
        "https://www.elivecd.org/premium/elive-for-servers/" \
        "https://www.elivecd.org/premium/elivim-neovim-framework/" \
        $NULL
        # "https://www.elivecd.org/premium/ai/" \

    # launch each one:
    premium_elivim
    premium_assistant
    premium_gptuuu
    premium_servers
    premium_synthwave_player


}

#
#  MAIN
#
main "$@"

# vim: set foldmethod=marker :
