#!/usr/bin/env python3
"""Run from an extracted Asterion folder to register its current location."""
from pathlib import Path
import os, shutil, subprocess
app = Path.cwd().resolve()
if not (app/'run.sh').is_file() or not (app/'asterion_app/app.py').is_file():
    raise SystemExit('Run this helper from the Asterion application folder.')
# Desktop Entry string escaping followed by Exec quoted-argument escaping.
def value(text):
    return str(text).replace('\\', '\\\\').replace('\n', '\\n').replace('\r', '\\r')
def argument(text):
    text = str(text).replace('%', '%%')
    for char in ('\\', '"', '`', '$'):
        text = text.replace(char, '\\'+char)
    return value('"'+text+'"')
base=Path(os.environ.get('XDG_DATA_HOME', str(Path.home()/'.local/share')))
entry=base/'applications/asterion.desktop'
icon_dir=base/'icons/hicolor/128x128/apps'
entry.parent.mkdir(parents=True,exist_ok=True)
icon_dir.mkdir(parents=True,exist_ok=True)
source_icon=app/'asterion_app/ui/assets/asterion.png'
if source_icon.is_file():shutil.copy2(source_icon,icon_dir/'asterion.png')
entry.write_text('[Desktop Entry]\nType=Application\nName=Asterion\nComment=Local-first personal productivity\nExec=/bin/bash '+argument(app/'run.sh')+'\nPath='+value(app)+'\nIcon=asterion\nTerminal=false\nCategories=Office;Utility;\n',encoding='utf-8')
if shutil.which('update-desktop-database'):
    subprocess.run(['update-desktop-database',str(entry.parent)],check=False)
print('Desktop entry created:',entry)
print('Regenerate this entry if you move the application folder.')
