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



#set -e
#trap "exit_ok" EXIT
trap "exit_error" 1 3 5 6 14 15 ERR TERM

exit_error(){
    exit 1
}

gui_info(){
    $guitool --info --text="$*"
}
gui_error(){
    $guitool --error --text="$*"
}
gui_confirm(){
    if $guitool --question --text="$@" ; then
        return 0
    else
        return 1
    fi
}

main(){
    # pre {{{
    local name magnet file

    if ! el_dependencies_check "transmission-cli|transmission-gtk|xclip|lynx" ; then
        el_dependencies_install "transmission-cli|transmission-gtk|xclip|lynx"
    fi

    # Usage
    if [[ -z "${1}" ]] || ! [[ -e "$1" ]] ; then
        gui_error "$(eval_gettext "You must select a file or directory to create a torrent from.")"
        exit 1
    fi

    local default_name
    default_name="$( basename "$1" )"
    default_name="${default_name%/}"
    if [[ -n "$2" ]] ; then
        default_name="${default_name} (+ extras)"
    fi

    name="$( $guitool --entry --text="$(eval_gettext "Enter the name for the destination path. This will be the name of the file or directory for the shared torrent.")" --entry-text="$default_name" )"

    if [[ -z "$name" ]] ; then
        gui_error "$(eval_gettext "The name for the torrent cannot be empty.")"
        exit 1
    fi

    name="${name// /_}"

    # check if transmission torrents directory is available (I use an external disk for them)
    download_dir="$( grep \"download-dir\" ~/.config/transmission/settings.json | sed -e 's|^.*": "||g' -e 's|",$||g' | tail -1 )"

    # check torrent downloads directory
    if [[ -z "$download_dir" ]] ; then
        gui_error "$( eval_gettext "First, run the 'Transmission' application and configure the downloads directory." )"
        exit 1
    fi
    if ! el_check_dirs "$download_dir" ; then
        if [[ -n "$download_dir" ]] ; then
            mkdir -p "$download_dir"
        fi
    fi
    if ! el_check_dirs "$download_dir" ; then
        gui_error "$( eval_gettext "Directory for downloading torrents from Transmission is not available, configure it in Transmission first" )"
        ( transmission-gtk & )
        exit 1
    fi

    # check name / files compatibility
    for file in "$@"
    do
        if echo -- "$(basename "$file" )" | grep --color=auto -E '(/|\\|\||\*|:)' ; then
            gui_error "Sorry, your directory or files cannot contain any of these characters: \\ | / * :"
            exit 1
        fi
    done


    # }}}


    # make a copy of what we want to share in order to seed them and from a temporal place
    mkdir -p "${download_dir}"

    if [[ -e "${download_dir}/$name" ]] ; then
        if gui_confirm "$(eval_gettext "Destination path already exists:")\n${download_dir}/${name}\n\n$(eval_gettext "Do you want to remove it to continue with a clean copy?")" ; then
            if [[ -x "$( which trash-put )" ]] ; then
                trash-put "${download_dir}/$name"
            else
                rm -rf "${download_dir}/$name"
            fi
        else
            NOREPORTS=1 gui_error "$( eval_gettext "Aborted by user." )"
            exit 1
        fi
    fi

    # if multiple arguments, or single argument is a directory, create a directory and copy into it
    (
    if (( $# > 1 )) || [[ -d "$1" ]] ; then
        mkdir -p "${download_dir}/$name"
        cp -a "$@" "${download_dir}/$name/"
    else
        # single file argument, copy it directly
        cp -a "$1" "${download_dir}/$name"
    fi
    ) | $guitool --progress --pulsate --auto-close --text="$(eval_gettext "Copying files to the seeding directory...")"

    cd "${download_dir}"



    # create a .torrent file
    # note: seems like using the -p option doesn't works, but privtracker provides a private tracker, in all other trackers there's a risk of unknonwn (possibly) public sharing
    #if timeout 15 lynx -dump "privtracker.com" | grep -qs "github.com/meehow/privtracker" ; then
        #transmission-create \
            #-c "Made in Elive Linux, the best OS ever, using the automated CLI tool '$(basename $0)'" \
            #-t "https://privtracker.com/p3r6p4hrhw51no4e/announce" \
            #-o "/tmp/${name}.torrent" \
            #"$name"
    #else
        ## main private tracker doesn't works, fallback to a full (working) list instead in order to continue making the tool working and not fail:
        #el_warning "Seems like the default private tracker is not working, we are going to use a full list instead"

        # updated good list of trackers: https://github.com/ngosang/trackerslist

        #if gui_confirm "Going to use a more complete list of trackers, this will make probably your torrent contents public, do you want to continue?" ; then
        if gui_confirm "$( eval_gettext "This torrent will likely be shared publicly since we are not using private trackers. Do you want to continue?" )" ; then
            torrent_file="/tmp/${name}.torrent"
            transmission-create \
                -c "Made in Elive Linux, the best OS ever, using the tool '$(basename "$0")'" \
                -t "https://privtracker.com/p3r6p4hrhw51no4e/announce" \
                -t "http://bt.okmp3.ru:2710/announce" \
                -t "http://nyaa.tracker.wf:7777/announce" \
                -t "http://share.camoe.cn:8080/announce" \
                -t "http://tracker.bt4g.com:2095/announce" \
                -t "http://tracker.files.fm:6969/announce" \
                -t "udp://208.83.20.20:6969/announce" \
                -t "udp://211.75.205.188:6969/announce" \
                -t "udp://31.38.161.123:6969/announce" \
                -t "udp://93.158.213.92:1337/announce" \
                -t "udp://open.stealth.si:80/announce" \
                -t "udp://t.overflow.biz:6969/announce" \
                -t "udp://tracker.bittor.pw:1337/announce" \
                -t "udp://tracker.dler.org:6969/announce" \
                -t "udp://tracker.filemail.com:6969/announce" \
                -t "udp://tracker.opentrackr.org:1337/announce" \
                -t "udp://tracker.srv00.com:6969/announce" \
                -t "udp://tracker.torrent.eu.org:451/announce" \
                -t "udp://wepzone.net:6969/announce" \
                -t "udp://tracker.theoks.net:6969/announce" \
                -t "udp://tracker.darkness.services:6969/announce" \
                -t "udp://tracker.corpscorp.online:80/announce" \
                -t "udp://tracker.004430.xyz:1337/announce" \
                -t "udp://leet-tracker.moe:1337/announce" \
                -t "udp://exodus.desync.com:6969/announce" \
                -t "udp://bittorrent-tracker.e-n-c-r-y-p-t.net:1337/announce" \
                -t "udp://6ahddutb1ucc3cp.ru:6969/announce" \
                -t "https://tracker.zhuqiy.com:443/announce" \
                -t "https://tracker.pmman.tech:443/announce" \
                -t "https://tracker.nekomi.cn:443/announce" \
                -t "https://tracker.moeblog.cn:443/announce" \
                -o "$torrent_file" \
                "$name"
        else
            NOREPORTS=1 gui_error "Aborted by user"
            exit 1
        fi
    #fi


    # get magnet link
    magnet="$( transmission-show -m "$torrent_file" )"

    ( printf "%s\n" "$magnet" | xclip -selection clipboard & )

    # show magnet link
    # escape for pango markup
    magnet_escaped="$( echo "$magnet" | sed 's/&/\&amp;/g' )"
    gui_info "$(eval_gettext "Magnet code copied to clipboard.")\n$(eval_gettext "Torrent file created on:") ${torrent_file}"


    # run transmission to start seeding it
    if [[ -d "$( grep \"download-dir\" ~/.config/transmission/settings.json | sed -e 's|^.*": "||g' -e 's|",$||g' )"  ]] ; then
        ( transmission-gtk "$torrent_file" 2>/dev/null & )

        gui_info "$( eval_gettext "After Transmission verifies local data, restart it to properly start sharing your torrent with others." )"

    else
        gui_error "$( eval_gettext "Directory for downloading torrents from Transmission is not available, create it first, then run transmission with the file:" )\n${torrent_file}"
    fi

    gui_info "$( eval_gettext "Your files are being shared via torrent now, using a copy of your original provided files." )"

}

#
#  MAIN
#
main "$@"

# vim: set foldmethod=marker :
