import urllib.request, json, base64, sys

import re
raw = open('/mnt/local-home/sirdrez-backup/.git-credentials').read().strip()
m = re.search(r'https://(\w+):(\S+)@gitea\.arisingmedia\.us', raw)
user, creds = m.group(1), m.group(2)
BASE  = 'https://gitea.arisingmedia.us/api/v1/repos/AM/bigbreath.co'
import base64 as _b64
HDR   = {
    'Authorization': 'Basic ' + _b64.b64encode(f'{user}:{creds}'.encode()).decode(),
    'Content-Type': 'application/json',
    'User-Agent': 'git/2.43.0',
    'Accept': 'application/json',
}
ROOT  = '/mnt/local-home/sirdrez-backup/arisingmedia-websites/bigbreath.co'

def get_sha(path):
    req = urllib.request.Request(f'{BASE}/contents/{path}', headers={'Authorization': 'token ' + creds})
    try:
        return json.load(urllib.request.urlopen(req, timeout=8))['sha']
    except urllib.error.HTTPError as e:
        if e.code == 404:
            return None
        raise

def put_file(path, local_path, msg):
    sha = get_sha(path)
    method = 'PUT' if sha else 'POST'
    payload = {'message': msg, 'content': base64.b64encode(open(local_path, 'rb').read()).decode()}
    if sha:
        payload['sha'] = sha
    req = urllib.request.Request(f'{BASE}/contents/{path}', data=json.dumps(payload).encode(), headers=HDR, method=method)
    d = json.load(urllib.request.urlopen(req, timeout=10))
    print(f'OK [{method}]: {path} | {d["content"]["sha"][:8]}')

put_file('.htaccess',        f'{ROOT}/.htaccess',        'Route / to coming_soon via PHP router')
put_file('.cpanel.yml',      f'{ROOT}/.cpanel.yml',      'Deploy .htaccess to public_html')
put_file('infra/nginx.conf', f'{ROOT}/infra/nginx.conf', 'Route / and catch-all to coming_soon')
