#!/usr/bin/env python3
#
# Software License Agreement (BSD)
#
# @author    Mike Purvis <mpurvis@clearpathrobotics.com>
# @author    Chris Iverach-Brereton <civerachb@clearpathrobotics.com>
# @copyright (c) 2014, Clearpath Robotics, Inc., All rights reserved.
# @usage     download_spinnaker {arch} {dir} {os-code-name}
#            e.g. download_spinnaker x86_64 /path/to/somewhere xenial
#
# Redistribution and use in source and binary forms, with or without modification, are permitted provided that
# the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this list of conditions and the
#   following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
#   following disclaimer in the documentation and/or other materials provided with the distribution.
# * Neither the name of Clearpath Robotics nor the names of its contributors may be used to endorse or
#   promote products derived from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED
# WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
# PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
# ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
# TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.

import glob
import http.cookiejar
import io
import logging
import os
import shutil
import subprocess
import sys
import tarfile
import urllib

logging.basicConfig(level=logging.INFO)

OS_LIBRARY_VERSION = {
    'focal': '20.04',
    'jammy': '22.04',
    'noble': '24.04',
}

ARCH_LINUX_ARCH = {
    'x86_64': 'amd64',
    'armv8': 'arm64',
}

arch = sys.argv[1]
destination_folder = sys.argv[2]
os_code_name = sys.argv[3]
spinnaker_version='4.2.0.88'

linux_arch = ARCH_LINUX_ARCH[arch]
os_version = OS_LIBRARY_VERSION[os_code_name]
archive_url = f'https://eventvisionresearch.com/Spinnaker/spinnaker-{spinnaker_version}-{linux_arch}-{os_version}-pkg.tar.gz'
print('archive url: ', archive_url)
folder_name = f'spinnaker-{spinnaker_version}-{linux_arch}'


print('CPU architecture is ', arch)
print('linux arch is ', linux_arch)
print('OS code name is ', os_code_name)
print('OS version is ', os_version)
print('Destination folder is ', destination_folder)

spinnaker_base = 'opt/spinnaker/lib'

if not os.path.exists(os.path.join(os.getcwd(), folder_name)):
    cj = http.cookiejar.CookieJar()
    opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj))
    opener.addheaders = [('User-agent', 'Mozilla/5.0'), ('Referer', 'https://www.ptgrey.com')]

    print('Downloading SDK archive from {0}...'.format(archive_url))
    resp = opener.open(archive_url)
    print('Unpacking tarball.')
    with tarfile.open(mode='r:gz', fileobj=io.BytesIO(resp.read())) as tar:
        tar.extractall()
    print('Unpacking debs.')
    debs = glob.glob(os.path.join(os.getcwd(), folder_name, '*.deb'))

    unpack_dir = os.path.join(os.getcwd())
    if not os.path.exists(unpack_dir):
        os.makedirs(unpack_dir)
    for deb in debs:
        print('Extracting {0}'.format(deb))
        subprocess.call(['dpkg', '--extract', deb, unpack_dir])

    # Copy the shared libraries into the output folder
    print('Copying libraries to {0}'.format(destination_folder))
    if not os.path.exists(destination_folder):
        os.makedirs(destination_folder)
    libs = glob.glob(os.path.join(os.getcwd(), spinnaker_base, 'libSpinnaker*.so*'))
    libs += glob.glob(os.path.join(os.getcwd(), spinnaker_base, 'libG*.so*'))
    libs += glob.glob(os.path.join(os.getcwd(), spinnaker_base, 'lib*Parser*.so*'))
    libs += glob.glob(os.path.join(os.getcwd(), spinnaker_base, 'libLog*.so*'))
    libs += glob.glob(os.path.join(os.getcwd(), spinnaker_base, 'libNodeMapData*.so*'))
    for lib in libs:
        print('Copying: {}'.format(os.path.basename(lib)))
        shutil.copyfile(lib, os.path.join(destination_folder, os.path.basename(lib)))
else:
    print('Previous installation found, skipping...')
