#!/usr/bin/env python3

import sys
import os
from os import path
from helpers import parse_configfile, run_command
from subprocess import check_call

def main():
    try:
        os.mkdir('libav_build')
    except:
        pass
    mydir = os.getcwd()
    extra_args = parse_configfile('common_options')
    for arg in parse_configfile('libav_options'):
        if arg == b'librtmp_magic':
            try:
                check_call('pkg-config --exists librtmp'.split())
            except:
                sys.exit('You have specified "librtmp_magic" in libav_options,'
                         'but running "pkg-config --exists librtmp" failed - '
                         "can't enable librtmp! Aborting.")
            extra_args.append('--enable-librtmp')
            cflags = run_command('pkg-config --cflags librtmp').strip()
            libs = run_command('pkg-config --libs librtmp').strip()
            extra_args.append(b'--extra-cflags=' + cflags)
            extra_args.append(b'--extra-libs=' + libs)
        else:
            extra_args.append(arg)

    args = ['--prefix=%s/build_libs' % mydir,
            '--enable-gpl',
            '--cpu=host',
            '--disable-debug',
            '--enable-pthreads',
            '--disable-shared', '--enable-static',
            '--disable-avdevice', '--disable-avfilter', '--disable-vaapi']
    executables = 'avconv ffmpeg avplay ffplay avserver ffserver ' \
                  'avprobe ffprobe'.split()
    for name in executables:
        if path.exists(path.join('libav', name + '.c')):
            args.append('--disable-' + name)

    executable = path.join(mydir, 'libav', 'configure')

    os.chdir('libav_build')
    check_call([executable] + args + extra_args)

main()
