#!/usr/bin/env python

import os
import shutil
import struct
import subprocess
import sys

ffmpeg_version = "4.2.2"
ffmpeg_package = "4"

destination_dir = sys.argv[1]
tarball_dir = "tarballs"


def get_platform():
    if sys.platform == "linux":
        return "manylinux_%s" % os.uname().machine
    elif sys.platform == "darwin":
        return "macosx_%s" % os.uname().machine
    elif sys.platform == "win32":
        return "win%s" % (struct.calcsize("P") * 8)
    else:
        raise Exception("Unsupported platfom %s" % sys.platform)


# work around buggy 'tar' executable on Windows
if sys.platform == "win32":
    os.environ["PATH"] = "C:\\Program Files\\Git\\usr\\bin;" + os.environ["PATH"]

# determine tarball name
tarball_name = "ffmpeg-%s-%s.tar.bz2" % (ffmpeg_version, get_platform())
tarball_url = "https://github.com/jlaine/pyav-ffmpeg/releases/download/%s-%s/%s" % (
    ffmpeg_version,
    ffmpeg_package,
    tarball_name,
)

# download tarball
tarball_file = os.path.join(tarball_dir, tarball_name)
if not os.path.exists(tarball_file):
    print("Downloading %s" % tarball_url)
    if not os.path.exists(tarball_dir):
        os.mkdir(tarball_dir)
    subprocess.check_call(
        ["curl", "--location", "--output", tarball_file, "--silent", tarball_url]
    )

# extract tarball
print("Extracting to %s" % destination_dir)
if os.path.exists(destination_dir):
    shutil.rmtree(destination_dir)
os.mkdir(destination_dir)
subprocess.check_call(["tar", "-C", destination_dir, "-xf", tarball_file])
