#!/usr/bin/env python3
"""Forward emails from LFCS Gmail to admin@lfcs.com.au via Gmail API."""
import sys
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 = sys.argv[1:]
if not msg_ids:
    print("Usage: fwd_emails.py <msg_id_1> <msg_id_2> ...")
    sys.exit(1)

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\n"
        f"To: admin@lfcs.com.au\r\n"
        f"Subject: Fwd: {orig_subject}\r\n"
        f"Content-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}/{len(msg_ids)}] Sent: {orig_subject[:60]} -> {result.get("id")}')

print('All forwarded.')