#!/usr/bin/env python3
from google.oauth2.credentials import Credentials
from google.auth.transport.requests import Request
import urllib.request, json, base64, email

creds = Credentials.from_authorized_user_file('/root/.hermes/google_token.json', ['https://www.googleapis.com/auth/gmail.readonly', 'https://www.googleapis.com/auth/gmail.send'])
creds.refresh(Request())

msg_ids = [
    '19e05250c696f51b',
    '19e00844da269f8e',
    '19e00178f3477e43',
    '19dfb9283585162a',
    '19dfb88630ccd528',
]

for i, msg_id in enumerate(msg_ids):
    url = f'https://gmail.googleapis.com/gmail/v1/users/me/messages/{msg_id}?format=raw'
    req = urllib.request.Request(url, headers={'Authorization': f'Bearer {creds.token}'})
    with urllib.request.urlopen(req) as r:
        data = json.loads(r.read())
        raw_b64 = data['raw']
        pad = len(raw_b64) % 4
        if pad: raw_b64 += '=' * (4 - pad)
        msg_bytes = base64.urlsafe_b64decode(raw_b64)

    original = email.message_from_bytes(msg_bytes)
    orig_subject = original.get('Subject', '(no subject)')

    fwd_raw = f"From: michael.mcloughlin@lfcs.com.au\r\nTo: admin@lfcs.com.au\r\nSubject: Fwd: {orig_subject}\r\nContent-Type: message/rfc822; charset=utf-8\r\n\r\n".encode('utf-8') + msg_bytes
    b64_fwd = base64.urlsafe_b64encode(fwd_raw).decode('ascii').rstrip('=')

    send_url = 'https://gmail.googleapis.com/gmail/v1/users/me/messages/send'
    body = json.dumps({'raw': b64_fwd}).encode('utf-8')
    send_req = urllib.request.Request(send_url, data=body, headers={
        'Authorization': f'Bearer {creds.token}',
        'Content-Type': 'application/json'
    })
    with urllib.request.urlopen(send_req) as r:
        result = json.loads(r.read())
        print(f'[{i+1}/5] Sent: {orig_subject[:60]} -> {result.get("id")}')

print('All forwarded.')