#!/usr/bin/env python3

import os
from os import path
from subprocess import check_call

from helpers import GitWrapper, run_command

def main():
    git = GitWrapper()

    # Update from versions using a submodule name different from "libav"
    p = None
    if path.exists('ffmpeg-mt/.git'):
        p = 'ffmpeg-mt'
    else:
        p = 'ffmpeg'
    switch_to_libav = not path.exists('libav/.git') and p
    if switch_to_libav:
        if p == 'ffmpeg-mt' and path.exists('ffmpeg-mt/libswscale/.git'):
            # Update from old version with libswscale as submodule
            os.system('cd ffmpeg-mt && rm -rf libswscale')
        os.rename(p, 'libav')
        try:
            # Rename the build dir mainly to get it cleaned up -
            # incremental builds probably won't work due to wrong absolute
            # paths recorded in .d files.
            os.rename('ffmpeg_build', 'libav_build')
        except:
            pass
        if path.exists('ffmpeg_options') and not path.exists('libav_options'):
            os.rename('ffmpeg_options', 'libav_options')
        for fname in ('ffmpeg-mt-enabled', 'ffmpeg-mt-disabled'):
            if path.exists(fname):
                os.remove(fname)
        check_call('git submodule init libav'.split())

    config = git.get_config()
    submodules = git.get_submodules()
    # Update existing submodules, but don't check out new ones
    for p in submodules:
        if not b'submodule.'+p+b'.url' in config:
            continue
        if not path.exists(path.join(p, b'.git')):
            continue
        check_call('git submodule update'.split() + [p])
    def cmd():
        check_call('git submodule update --init'.split())
    git.foreach_submodule(cmd)

    if switch_to_libav:
        print()
        print("The ffmpeg-mt submodule directory has been renamed to libav.")
        print("The contents of the submodule have already been based on")
        print("the Libav project for some time (FFmpeg-mt was merged to it).")
        print("The ffmpeg_options file has been renamed to libav_options.")
        print("You should run ./clean before recompiling due to the switch.")

main()
