#!/usr/bin/env python3
import subprocess, sys, os

# download MesloLGS NF
meslo = "/tmp/MesloLGS NF Regular.ttf"
if not os.path.exists(meslo):
    meslo_url = "https://github.com/ryanoasis/nerd-fonts/releases/latest/download/Meslo.tar.xz"
    subprocess.run(["curl", "-sL", "-o", "/tmp/Meslo.tar.xz", meslo_url], check=True)
    subprocess.run(["tar", "xf", "/tmp/Meslo.tar.xz", "-C", "/tmp", "MesloLGSNerdFont-Regular.ttf"], check=True)
    os.rename("/tmp/MesloLGSNerdFont-Regular.ttf", meslo)

# download SVG icons
base = "https://git.syui.ai/ai/app/raw/branch/main/icon"
for name in ["ai.svg", "syui.svg", "bluesky.svg"]:
    subprocess.run(["curl", "-sL", "-o", f"/tmp/{name}", f"{base}/{name}"], check=True)

subprocess.run(["fontforge", "-script", "/dev/stdin"], input=b"""
import fontforge

icons = fontforge.font()
icons.em = 1024

scale = 200

glyph = icons.createChar(0xE001, "ai")
glyph.importOutlines("/tmp/ai.svg")
bb = glyph.boundingBox()
glyph.transform((scale/100.0, 0, 0, scale/100.0, 0, 0))
glyph.width = 1024

glyph = icons.createChar(0xE002, "syui")
glyph.importOutlines("/tmp/syui.svg")
glyph.transform((scale/100.0, 0, 0, scale/100.0, 0, 0))
glyph.width = 1024

glyph = icons.createChar(0xE003, "bluesky")
glyph.importOutlines("/tmp/bluesky.svg")
glyph.transform((scale/100.0, 0, 0, scale/100.0, 0, 0))
glyph.width = 1024

icons.generate("/tmp/icons.ttf")
icons.close()

font = fontforge.open("/tmp/MesloLGS NF Regular.ttf")
font.selection.select(0xE001)
font.clear()
font.selection.select(0xE002)
font.clear()
font.selection.select(0xE003)
font.clear()
font.selection.none()

font.mergeFonts("/tmp/icons.ttf")

font.fontname = "aifont"
font.familyname = "aifont"
font.fullname = "aifont"
font.appendSFNTName("English (US)", "Family", "aifont")
font.appendSFNTName("English (US)", "SubFamily", "Regular")
font.appendSFNTName("English (US)", "UniqueID", "aifont-regular")
font.appendSFNTName("English (US)", "Fullname", "aifont")
font.appendSFNTName("English (US)", "PostScriptName", "aifont")
font.appendSFNTName("English (US)", "Preferred Family", "aifont")
font.appendSFNTName("English (US)", "Preferred Styles", "Regular")

font.generate("/tmp/aifont.ttf")
font.close()
print("done: /tmp/aifont.ttf")
""", check=True)
