#!/usr/bin/env python

import os
import shutil
import struct
import subprocess
import sys

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)


# determine tarball name
tarball_name = "codecs-%s.tar.gz" % get_platform()
tarball_url = (
    "https://github.com/aiortc/aiortc-codecs/releases/download/1.1/%s" % 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])
