# Buggy code
def execute():
    language = frappe.get_single("System Settings").language

    if language and language.startswith("en"):
        return

    frappe.local.lang = language

    all_domains = frappe.get_hooks("domains")

    for domain in all_domains:
        translated_domain = _(domain, lang=language)
        if frappe.db.exists("Domain", translated_domain):
            frappe.rename_doc(
                "Domain", translated_domain, domain, ignore_permissions=True, merge=True
            )

    domain_settings = frappe.get_single("Domain Settings")
    active_domains = [d.domain for d in domain_settings.active_domains]

    try:
        for domain in active_domains:
            domain = frappe.get_doc("Domain", domain)
            domain.setup_domain()

            if int(frappe.db.get_single_value("System Settings", "setup_complete")):
                domain.setup_sidebar_items()
                domain.setup_desktop_icons()
                domain.set_default_portal_role()
    except frappe.LinkValidationError:
        pass


# Traceback (frappe.exceptions.ValidationError)
nadivia@ID16595:/home/frappe/frappe-bench$ sudo bench update
INFO:bench.utils:updating bench
INFO:bench.utils:git pull
Already up-to-date.
INFO:bench.utils:./env/bin/pip install Pillow
Requirement already satisfied: Pillow in ./env/lib/python2.7/site-packages
Requirement already satisfied: olefile in ./env/lib/python2.7/site-packages (from Pillow)
INFO:bench.app:pulling frappe
INFO:bench.utils:git pull  upstream master
Da https://github.com/frappe/frappe
* branch            master     -> FETCH_HEAD
Already up-to-date.
INFO:bench.utils:find . -name "*.pyc" -delete
INFO:bench.app:pulling erpnext
INFO:bench.utils:git pull  upstream master
Da https://github.com/frappe/erpnext
* branch            master     -> FETCH_HEAD
Already up-to-date.
INFO:bench.utils:find . -name "*.pyc" -delete
Updating Python libraries...
INFO:bench.utils:./env/bin/pip install --upgrade pip
Requirement already up-to-date: pip in ./env/lib/python2.7/site-packages
INFO:bench.utils:./env/bin/pip install -q -r /home/frappe/.bench/requirements.txt
INFO:bench.utils:./env/bin/pip install -q -r ./apps/erpnext/requirements.txt
INFO:bench.utils:./env/bin/pip install -q -r ./apps/frappe/requirements.txt
Updating node libraries...
INFO:bench.utils:npm install
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@^1.0.0 (node_modules/chokidar/node_modules/fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.1.3: wanted {"os":"darwin","arch":"any"} (current: {"os":"linux","arch":"x64"})
npm WARN frappe@ No description
Backing up sites...
Patching sites...
Migrating site1.local
Executing erpnext.patches.v9_2.rename_translated_domains_in_en in site1.local (1bd3e0294da19198)
Traceback (most recent call last):
File "/usr/lib/python2.7/runpy.py", line 174, in _run_module_as_main
"__main__", fname, loader, pkg_name)
File "/usr/lib/python2.7/runpy.py", line 72, in _run_code
exec code in run_globals
File "/home/frappe/frappe-bench/apps/frappe/frappe/utils/bench_helper.py", line 94, in <module>
main()
File "/home/frappe/frappe-bench/apps/frappe/frappe/utils/bench_helper.py", line 18, in main
click.Group(commands=commands)(prog_name='bench')
File "/home/frappe/frappe-bench/env/local/lib/python2.7/site-packages/click/core.py", line 722, in __call__
return self.main(*args, **kwargs)
File "/home/frappe/frappe-bench/env/local/lib/python2.7/site-packages/click/core.py", line 697, in main
rv = self.invoke(ctx)
File "/home/frappe/frappe-bench/env/local/lib/python2.7/site-packages/click/core.py", line 1066, in invoke
return _process_result(sub_ctx.command.invoke(sub_ctx))
File "/home/frappe/frappe-bench/env/local/lib/python2.7/site-packages/click/core.py", line 1066, in invoke
return _process_result(sub_ctx.command.invoke(sub_ctx))
File "/home/frappe/frappe-bench/env/local/lib/python2.7/site-packages/click/core.py", line 895, in invoke
return ctx.invoke(self.callback, **ctx.params)
File "/home/frappe/frappe-bench/env/local/lib/python2.7/site-packages/click/core.py", line 535, in invoke
return callback(*args, **kwargs)
File "/home/frappe/frappe-bench/env/local/lib/python2.7/site-packages/click/decorators.py", line 17, in new_func
return f(get_current_context(), *args, **kwargs)
File "/home/frappe/frappe-bench/apps/frappe/frappe/commands/__init__.py", line 24, in _func
ret = f(frappe._dict(ctx.obj), *args, **kwargs)
File "/home/frappe/frappe-bench/apps/frappe/frappe/commands/site.py", line 217, in migrate
migrate(context.verbose, rebuild_website=rebuild_website)
File "/home/frappe/frappe-bench/apps/frappe/frappe/migrate.py", line 31, in migrate
frappe.modules.patch_handler.run_all()
File "/home/frappe/frappe-bench/apps/frappe/frappe/modules/patch_handler.py", line 29, in run_all
if not run_single(patchmodule = patch):
File "/home/frappe/frappe-bench/apps/frappe/frappe/modules/patch_handler.py", line 63, in run_single
return execute_patch(patchmodule, method, methodargs)
File "/home/frappe/frappe-bench/apps/frappe/frappe/modules/patch_handler.py", line 83, in execute_patch
frappe.get_attr(patchmodule.split()[0] + ".execute")()
File "/home/frappe/frappe-bench/apps/erpnext/erpnext/patches/v9_2/rename_translated_domains_in_en.py", line 16, in execute
frappe.rename_doc("Domain", translated_domain, domain, ignore_permissions=True, merge=True)
File "/home/frappe/frappe-bench/apps/frappe/frappe/__init__.py", line 696, in rename_doc
return rename_doc(*args, **kwargs)
File "/home/frappe/frappe-bench/apps/frappe/frappe/model/rename_doc.py", line 39, in rename_doc
new = validate_rename(doctype, new, meta, merge, force, ignore_permissions)
File "/home/frappe/frappe-bench/apps/frappe/frappe/model/rename_doc.py", line 117, in validate_rename
frappe.msgprint(_("{0} {1} does not exist, select a new target to merge").format(doctype, new), raise_exception=1)
File "/home/frappe/frappe-bench/apps/frappe/frappe/__init__.py", line 309, in msgprint
_raise_exception()
File "/home/frappe/frappe-bench/apps/frappe/frappe/__init__.py", line 284, in _raise_exception
raise ValidationError(encode(msg))
frappe.exceptions.ValidationError: Domain Manufacturing non esiste, selezionare un nuovo obiettivo da unire

# Fixed code
def execute():
    language = frappe.get_single("System Settings").language

    if language and language.startswith("en"):
        return

    frappe.local.lang = language

    all_domains = frappe.get_hooks("domains")

    for domain in all_domains:
        translated_domain = _(domain, lang=language)
        if frappe.db.exists("Domain", translated_domain):
            # if domain already exists merged translated_domain and domain
            merge = False
            if frappe.db.exists("Domain", domain):
                merge = True

            frappe.rename_doc(
                "Domain",
                translated_domain,
                domain,
                ignore_permissions=True,
                merge=merge,
            )

    domain_settings = frappe.get_single("Domain Settings")
    active_domains = [d.domain for d in domain_settings.active_domains]

    try:
        for domain in active_domains:
            domain = frappe.get_doc("Domain", domain)
            domain.setup_domain()

            if int(frappe.db.get_single_value("System Settings", "setup_complete")):
                domain.setup_sidebar_items()
                domain.setup_desktop_icons()
                domain.set_default_portal_role()
    except frappe.LinkValidationError:
        pass