# Copyright (c) Sandro Tosi, 2023, under the terms of dput-ng.

# Installation & setup guide (similar to the twitter hook, refer to that if unclear)

# 1. register an application on the Mastodon instance you want to publish messages to
# 2. save the application access token and instance API endpoint in ~/.config/dput-ng/mastodon.json
#    (sample at skel/mastodon.json)
# 3. run `sudo apt install python3-mastodon`
# 4. set up the hook by copying skel/toot.json to ~/.dput.d/hooks/
#    and code/toot.py to ~/.dput.d/scripts/
# 5. edit ~/.dput.d/profiles/ftp-master.json to add "toot" as an extra hook

import json
import os

from mastodon import Mastodon


def toot(changes, profile, interface):
    toot = "I've just uploaded %s/%s to %s #debian" % (
        changes['Source'],
        changes['Version'],
        changes['Distribution']
    )
    # https://fedi.tips/why-do-some-people-on-mastodon-and-the-fediverse-have-bigger-character-limits/
    if len(toot) > 500:
        toot = toot[:500]

    with open(os.path.expanduser("~/.config/dput-ng/mastodon.json"), 'r') as f:
        obj = json.load(f)
    m = Mastodon(
        access_token=obj["access_token"],
        api_base_url=obj["api_base_url"]
    )

    m.toot(toot)
