#!/usr/bin/env python3
# Copyright 2021 The Emscripten Authors.  All rights reserved.
# Emscripten is available under two separate licenses, the MIT license and the
# University of Illinois/NCSA Open Source License.  Both these licenses can be
# found in the LICENSE file.

"""Build and publish the emscripten website.

This script builds the emscripten website from source and creates a
new commit & branch in the emscripten-site repository containing any
changes.
"""

import os
import subprocess
import sys

script_dir = os.path.dirname(os.path.abspath(__file__))
root_dir = os.path.dirname(os.path.dirname(script_dir))
site_dir = os.path.join(root_dir, 'site')

message_template = '''\
Automatic update of the emscripten website

This is an automated change generated by `tools/maint/update_website.py` in the emscripten repo.

The change was generated at git revision https://github.com/emscripten-core/emscripten/commit/%s
'''


def is_git_clean(dirname):
  return not subprocess.check_output(['git', 'status', '-uno', '--porcelain'], text=True, cwd=dirname).strip()


def get_changed_files(dirname):
  files_changed = subprocess.check_output(['git', 'status', '-uno', '--porcelain'], text=True, cwd=dirname).splitlines()
  return [line[3:].strip() for line in files_changed]


def main(args):
  if args:
    site_out = args[0]
  else:
    site_out = os.path.join(root_dir, 'site', 'emscripten-site')

  assert os.path.isdir(site_out)
  print(f'Updating docs in: {site_out}')
  if not is_git_clean(site_out):
    print(f'{site_out}: tree is not clean')
    return 1
  if not is_git_clean(root_dir):
    print(f'{root_dir}: tree is not clean')
    return 1

  # Ensure the -site checkout is up-to-date
  subprocess.check_call(['git', 'fetch', 'origin'], cwd=site_out)
  subprocess.check_call(['git', 'checkout', 'origin/gh-pages'], cwd=site_out)

  # Build and install the docs
  subprocess.check_call(['make', 'install', f'EMSCRIPTEN_SITE={site_out}'], cwd=site_dir)

  files_changed = get_changed_files(site_out)
  if not files_changed:
    print('docs are up-to-date; no changes found')
    return 0

  # Create a new branch and commit the changes.
  subprocess.check_call(['git', 'checkout', '-b', 'update'], cwd=site_out)
  subprocess.check_call(['git', 'add', '.'], cwd=site_out)
  hash = subprocess.check_output(['git', 'rev-parse', '--short', 'HEAD'], text=True, cwd=root_dir).strip()
  message = message_template % hash
  subprocess.run(['git', 'commit', '-F', '-'], input=message, text=True, cwd=site_out)
  return 2


if __name__ == '__main__':
  sys.exit(main(sys.argv[1:]))
