#!/usr/bin/env bash
# ============================================================
# Autor: kamowski & AI
# Názov: gnote-export-to-txt
#   Gnote (Linux) – Notes Exporter: XML to TXT + ZIP
#
# Aplikácia:
#   Gnote – desktopová poznámková aplikácia pre Linux.
#
#------------------------------------------------------
# Popis:
#   Exportuje poznámky Gnote z aktuálneho pracovného adresára
#   do samostatných textových súborov (.txt) v kódovaní UTF-8
#   a vytvorí ZIP archív obsahujúci všetky exportované poznámky.
#
# Funkcie:
#   - Spracúva iba súbory .note v aktuálnom adresári.
#   - Nemení ani nemaže pôvodné súbory Gnote.
#   - Bezpečne rieši duplicitné názvy poznámok.
#   - Podporuje kódovanie UTF-8 vrátane diakritiky.
#   - Vytvára ZIP archív všetkých exportovaných TXT súborov.
#
# Požiadavky:
#   - Bash
#   - Python 3
#
# Použitie:
#   1. Vytvor niekde kópiu adresára ~/.local/share/gnote.
#   2. Rozbaľ všetky podadresáre tak, aby boli všetky
#      súbory .note priamo v jednom adresári.
#   3. V tomto adresári spusti:
#      ./gnote-export-to-txt.sh
#
# Výstup:
#   ./gnote-notes-in-txt/
#   ./gnote2txt.zip
#------------------------------------------------------
# Application:
#   Gnote – a desktop note-taking application for Linux.
#
# Description:
#   Exports Gnote notes from the current working directory
#   into individual UTF-8 plain text (.txt) files and creates
#   a ZIP archive containing the exported notes.
#
# Features:
#   - Processes only .note files in the current directory.
#   - Does not modify or delete original Gnote files.
#   - Handles duplicate note titles safely.
#   - Supports UTF-8 encoding.
#   - Creates a ZIP archive of all exported TXT files.
#
# Requirements:
#   - Bash
#   - Python 3
#
# Verzia: 08.11.2026–20:35
# Usage:
#   - Create a copy of the ~/.local/share/gnote directory in your working directory.
#   - Move all .note files from subdirectories into a single directory
#   - Run the gnote-export-to-txt.sh script from that directory.
#   chmod +x gnote-export-to-txt.sh
#   ./gnote-export-to-txt.sh
#
# Output:
#   ./gnote-notes-in-txt/
#   ./gnote2txt.zip
# ============================================================

set -euo pipefail

# Gnote XML to TXT exporter
# Works ONLY in the current directory.
# Original .note files are never modified.

WORKDIR="$(pwd)"
OUTDIR="$WORKDIR/gnote-notes-in-txt"
ZIPFILE="$WORKDIR/gnote2txt.zip"

if ! command -v python3 >/dev/null 2>&1; then
    echo "ERROR: python3 is required."
    exit 1
fi

shopt -s nullglob
NOTES=("$WORKDIR"/*.note)

if [ ${#NOTES[@]} -eq 0 ]; then
    echo "No .note files found in current directory."
    exit 1
fi

mkdir -p "$OUTDIR"

python3 - "$OUTDIR" "${NOTES[@]}" <<'PY'
import sys
import os
import re
import xml.etree.ElementTree as ET

outdir = sys.argv[1]
files = sys.argv[2:]

def find_element(root, name):
    for element in root.iter():
        if element.tag.split('}')[-1] == name:
            return element
    return None

def clean_filename(name):
    name = re.sub(r'[<>:"/\\|?*\x00-\x1f]', '_', name)
    name = re.sub(r'\s+', ' ', name).strip(' .')
    return name[:150] or "untitled"

used = set()

for path in files:
    try:
        tree = ET.parse(path)
        root = tree.getroot()

        title_node = find_element(root, 'title')
        content_node = find_element(root, 'note-content')

        title = ''.join(title_node.itertext()).strip() if title_node is not None else ""
        content = ''.join(content_node.itertext()) if content_node is not None else ""

        filename = clean_filename(title or os.path.basename(path).removesuffix('.note'))

        candidate = filename
        counter = 2

        while candidate.casefold() in used:
            candidate = f"{filename} ({counter})"
            counter += 1

        used.add(candidate.casefold())

        destination = os.path.join(outdir, candidate + ".txt")

        with open(destination, 'w', encoding='utf-8') as output:
            output.write(content)
            output.write('\n')

        print(f"OK: {os.path.basename(path)} -> {candidate}.txt")

    except Exception as error:
        print(f"ERROR: {os.path.basename(path)}: {error}")

print(f"\nExported {len(used)} notes.")
PY

# Create ZIP archive
rm -f "$ZIPFILE"
python3 - "$OUTDIR" "$ZIPFILE" <<'PY'
import os
import sys
import zipfile

folder, archive = sys.argv[1:]

with zipfile.ZipFile(archive, 'w', zipfile.ZIP_DEFLATED) as z:
    for root, dirs, files in os.walk(folder):
        for filename in files:
            path = os.path.join(root, filename)
            z.write(path, os.path.relpath(path, os.path.dirname(folder)))

print("ZIP archive created:", archive)
PY

echo
echo "Export completed."
echo "TXT files: $OUTDIR"
echo "ZIP archive: $ZIPFILE"
