#!/usr/bin/python3

"""From a text file, containing the text of a song, toot it (send it
to the fediverse)."""

# https://github.com/halcy/Mastodon.py
from mastodon import Mastodon

import os
import random
import time

SONG='voir.txt'
CHECKPOINT='checkpoint.data'
MAXSLEEP=3600

try:
    cp = open(CHECKPOINT)
    previous = cp.readline()
    chunk = int(cp.readline())
    cp.close()
except FileNotFoundError:
    previous = None
    chunk = 1
file = open(SONG)
line = 0
i = 0
c = ""
while i < chunk:
    l = file.readline()
    line += 1
    if l == "":
        break
    if l[:-1] == "":
        i += 1
    elif i == chunk-1:
        c += l

if l != "" and c != "":
    mastodon = Mastodon(
        client_id = 'voirapp_clientcred.secret',
        access_token = 'voirapp_usercred.secret',
        api_base_url = 'https://botsin.space/')
    generator = random.Random()
    generator.seed()
    time.sleep(generator.randint(1, MAXSLEEP))
    if chunk == 1:
        rid = None
    else:
        rid = previous
    result = mastodon.status_post(c, in_reply_to_id=rid, visibility='public')
    cp = open(CHECKPOINT, 'w')
    print(result['id'], file=cp)
    print(chunk+1, file=cp)
    cp.close()
else:
    os.remove(CHECKPOINT)

