#!/usr/bin/env python3
import sys
import shutil
import subprocess
import os
import time


"""
DropBy
Author: Jacob Vlijm
Copyright © 2017-2022 Ubuntu Budgie Developers
Website=https://ubuntubudgie.org
This program is free software: you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free Software
Foundation, either version 3 of the License, or any later version. This
program is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE. See the GNU General Public License for more details. You
should have received a copy of the GNU General Public License along with this
program.  If not, see <https://www.gnu.org/licenses/>.
"""


source = sys.argv[1]
name = sys.argv[2]


def notify_result(n):
    err = [
        "A permission error occurred",
        "Copying was cancelled",
        "An unexpected error occurred",
        "Successfully copied " + source + " to " + target
    ]
    message = err[n]
    sendmessage("Copy result", message, "media-flash-symbolic")


def sendmessage(title, message, icon=""):
    subprocess.Popen(["notify-send", "-i", icon, title, message])


def check_permissions(target):
    testf = os.path.join(target, ".check")
    try:
        open(testf, "wt")
    except PermissionError:
        notify_result(0)
    except Exception:
        notify_result(2)
    else:
        os.remove(testf)
        return True


def cont(source, targetdir):
    subprocess.Popen(["/usr/bin/xdg-open", target])
    time.sleep(0.5)
    try:
        question = subprocess.check_output([
            "/usr/bin/zenity", "--question",
            "--title", "Directory exists",
            "--text", "A previous copy exists. Please remove it first.",
            "--ok-label=Proceed", "--cancel-label=Cancel",
        ]).decode("utf-8")
    except subprocess.CalledProcessError:
        notify_result(1)
    else:
        try:
            shutil.copytree(source, targetdir, symlinks=True)
        except Exception:
            notify_result(2)
        else:
            notify_result(3)


def copy(source, targetdir):
    try:
        shutil.copytree(source, targetdir, symlinks=True)
    except FileExistsError:
        cont(source, targetdir)
    except Exception:
        notify_result(2)
    else:
        notify_result(3)


# get targeted path
user = os.environ["USER"]
cptrigger = "/tmp/" + user + "_dropby_icon_copy"
try:
    target = subprocess.check_output([
        "/usr/bin/zenity", "--file-selection", "--directory",
        '--title=Choose a target directory',
    ]).decode("utf-8").strip()
except subprocess.CalledProcessError:
    pass
# succeeded getting path, check permission
else:
    permission = check_permissions(target)
    if permission:
        open(cptrigger, "wt").write("")
        targetdir = os.path.join(target, name)
        copy(source, targetdir)
# make sure trigger is removed anyway
try:
    os.remove(cptrigger)
except FileNotFoundError:
    pass
