#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
from fontTools.ttLib import TTFont

def modify_font_metrics(input_font_path, output_font_path, scale=0.1):
    font = TTFont(input_font_path)

    # hhea is a required table but stranger things have happened
    # but start with these metrics
    hhea = font['hhea']
    my_ascender = hhea.ascent
    my_descender = hhea.descent
    my_linegap = hhea.lineGap

    # os2 is an optional table but is very common
    os2 = font['OS/2']

    # if hhea has no height and OS2 exists fallback to usWin Ascent and Descent
    if my_ascender == 0 and os2:
        my_ascender = os2.usWinAscent
        my_descender = -1 * os2.usWinDescent
        my_linegap = 0
    
    if os2:
        use_typo_metrics  = (os2.fsSelection & (1 << 7)) > 0
        if not use_typo_metrics:
            # do not trust current values and use hhea values to update them
            os2.sTypoAscender = my_ascender
            os2.sTypoDescender = my_descender
            os2.sTypoLineGap = my_linegap
            if os2.version < 4:
                os2.version = 4
            os2.fsSelection = os2.fsSelection | (1 << 7)
        else:
            my_ascender = os2.sTypoAscender
            my_descender = os2.sTypoDescender
            my_linegap = os2.sTypoLineGap
            # update hhea values to match sTypo values
            hhea.ascent = my_ascender
            hhea.descent = my_descender
            hhea.lineGap = my_linegap

    my_lineheight = my_ascender - my_descender + my_linegap
    new_line_gap = int(scale * my_lineheight)

    # update metrics to use new line gap values 
    hhea.lineGap = new_line_gap
    if os2:
        os2.sTypoLineGap = new_line_gap

    name_table = font['name']
    scale_suffix = f"-ls{int((1.0 + scale) * 100)}"

    for name_record in name_table.names:
        # Change name inside: "Font Family Name", "Full Font Name", "PostScript Name"
        if name_record.nameID in [1, 4, 6]:
            new_name = name_record.toUnicode() + scale_suffix
            name_record.string = new_name.encode(name_record.getEncoding())

    font.save(output_font_path)

# Sample
# input_font_path = "./IBMPlexMono-Regular.ttf"
# output_font_path = "./IBMPlexMono-Regular-modified7.ttf"
input_font_path = "./LiberationMono-Regular.ttf"
output_font_path = "./LiberationMono-modified.ttf"
modify_font_metrics(input_font_path, output_font_path, scale=0.5)
