# -*- coding: utf-8 -*-
"""Bascule tout le site d'un domaine a un autre.
   Usage : python3 domaine.py <ancien-domaine> <nouveau-domaine>
   Exemple le jour du changement :
       python3 domaine.py https://future.micronics.fr https://www.micronics.fr
   Touche : canonical, versions linguistiques, donnees structurees, sitemap, robots.txt.
"""
import io, os, sys, glob

def main(ancien, nouveau):
    base = os.path.dirname(os.path.abspath(__file__))
    os.chdir(base)
    for d in (ancien, nouveau):
        if not d.startswith('http') or d.endswith('/'):
            raise SystemExit('Domaine attendu sous la forme https://exemple.fr (sans / final)')
    cibles = sorted(glob.glob('*.html')) + sorted(glob.glob('en/*.html')) \
           + [f for f in ('sitemap.xml', 'robots.txt') if os.path.exists(f)]
    total = 0; touches = 0
    for f in cibles:
        s = io.open(f, encoding='utf-8', errors='surrogateescape').read()
        n = s.count(ancien)
        if n:
            io.open(f, 'w', encoding='utf-8', errors='surrogateescape').write(s.replace(ancien, nouveau))
            total += n; touches += 1
    print('%d remplacement(s) dans %d fichier(s) : %s -> %s' % (total, touches, ancien, nouveau))
    print('Pensez a redeposer sitemap.xml et robots.txt, et a le signaler dans la Search Console.')

if __name__ == '__main__':
    if len(sys.argv) != 3:
        raise SystemExit(__doc__)
    main(sys.argv[1], sys.argv[2])
