# make-icon-pack.py: the iOS, Android and web icon sizes from one square PNG (pip install pillow)
# usage: python3 make-icon-pack.py icon.png [out-folder]
import json, sys
from pathlib import Path
from PIL import Image

LAUNCHER = {'mdpi': 48, 'hdpi': 72, 'xhdpi': 96, 'xxhdpi': 144, 'xxxhdpi': 192}

def opaque(im):
    """App stores want no transparency: lay it on the icon's top-edge colour (white if that is clear)."""
    if im.mode == 'RGB':
        return im
    rgba = im.convert('RGBA')
    top = rgba.getpixel((rgba.width // 2, 2))
    base = Image.new('RGBA', rgba.size, top if top[3] == 255 else (255, 255, 255, 255))
    return Image.alpha_composite(base, rgba).convert('RGB')

def save(im, path, px):
    path.parent.mkdir(parents=True, exist_ok=True)
    im.resize((px, px), Image.LANCZOS).save(path, optimize=True)

src, out = sys.argv[1], Path(sys.argv[2] if len(sys.argv) > 2 else 'icons')
im = Image.open(src)
if im.width != im.height:
    sys.exit('use a square image')
master = opaque(im)

ios = out / 'ios' / 'AppIcon.appiconset'
save(master, ios / 'AppIcon.png', 1024)
(ios / 'Contents.json').write_text(json.dumps({
    'images': [{'filename': 'AppIcon.png', 'idiom': 'universal', 'platform': 'ios', 'size': '1024x1024'}],
    'info': {'author': 'xcode', 'version': 1},
}, indent=2))

for density, px in LAUNCHER.items():
    save(master, out / 'android' / 'res' / f'mipmap-{density}' / 'ic_launcher.png', px)
save(master, out / 'android' / 'ic_launcher-playstore.png', 512)

web = out / 'web'
save(master, web / 'apple-touch-icon.png', 180)
save(master, web / 'icon-192.png', 192)
save(master, web / 'icon-512.png', 512)
master.save(web / 'favicon.ico', sizes=[(16, 16), (32, 32), (48, 48)])
