#!/bin/bash

#
# DaVinci Resolve Multi Debian package creator
# Release 2020-12-15
# By Daniel Tufvesson
#
MAKERESOLVEDEB_VERSION=1.4.2

check_command() {
    echo -n "Checking for ${1}..."
    if [[ ! -x "$(command -v $1)" ]]; then
	echo "Missing! Sorry, need '$1' to continue."
	exit 1
    fi
    echo "found!"
}

copy_object() {
    if [[ -e "$1" ]] ; then
	#echo "[COPY] $1 [TO] $2"
	if ! cp -rp "$1" "$2";
	then
	    ERRORS=$((ERRORS+1))
	fi
    else
	echo "[ERROR: MISSING] $1"
	ERRORS=$((ERRORS+1))
    fi
}

assert_object() {
    if ! [[ -e "$1" ]] ; then
	echo "[ERROR: MISSING] $1"
	ERRORS=$((ERRORS+1))
    fi
}

link_object() {
    #echo "[LINK] $2 [TO] $1"
    ln -s "$1" "$2"
}

create_directory() {
    if [[ -e "$1" ]] ; then
	echo "[ERROR: DIRECTORY EXISTS] $1"
	ERRORS=$((ERRORS+1))
    else
	#echo "[CREATE DIRECTORY] $1"
	mkdir -p "$1"
    fi
}

createf_directory() {
    if [[ -e "${1}" ]] ; then
	chmod a+w -R ${1}
	rm -rf ${1}
    fi
    create_directory "$1"
}

remove_directory() {
    if [[ -e "${1}" ]] ; then
	chmod a+w -R ${1}
	rm -rf ${1}
    else
	echo "[ERROR: MISSING] $1"
	ERRORS=$((ERRORS+1))
    fi
}

extract_tgz() {
    if [[ -f "$1" ]] ; then
	#echo "[EXTRACT] $1 [TO] $2/$3"
	tar -zxf "$1" -C "$2" "$3"
    else
	echo "[ERROR: MISSING] $1"
	ERRORS=$((ERRORS+1))
    fi
}

make_executable() {
    if [[ -e "$1" ]] ; then
	#echo "[MAKE EXECUTABLE] $1"
	chmod a+x "$1"
    else
	echo "[ERROR: MISSING] $1"
	ERRORS=$((ERRORS+1))
    fi
}

init_deb() {
    create_directory ${DEB_DIR}/DEBIAN
    cat > ${DEB_DIR}/DEBIAN/control <<EOF
Package: ${DEB_NAME}
Version: ${DEB_VERSION}
Architecture: amd64
Maintainer: Blackmagic Design
Description: ${RESOLVE_NAME} made from ${INSTALLER_ARCHIVE} using MakeResolveDeb ${MAKERESOLVEDEB_VERSION}
Conflicts: ${DEB_CONFLICTS}
EOF
    echo "#!/bin/sh" > ${DEB_DIR}/DEBIAN/postinst
    echo "#!/bin/sh" > ${DEB_DIR}/DEBIAN/postrm
    create_directory ${DEB_DIR}/usr/share/applications/
}

close_deb() {
    echo "exit 0" >> ${DEB_DIR}/DEBIAN/postinst
    make_executable ${DEB_DIR}/DEBIAN/postinst
    echo "exit 0" >> ${DEB_DIR}/DEBIAN/postrm
    make_executable ${DEB_DIR}/DEBIAN/postrm
}

process15() {
    # Create directories
    create_directory ${RESOLVE_BASE_DIR}/configs
    create_directory ${RESOLVE_BASE_DIR}/easyDCP
    create_directory ${RESOLVE_BASE_DIR}/logs
    create_directory ${RESOLVE_BASE_DIR}/scripts
    create_directory ${RESOLVE_BASE_DIR}/.LUT
    create_directory ${RESOLVE_BASE_DIR}/.license
    create_directory ${RESOLVE_BASE_DIR}/.crashreport
    create_directory ${RESOLVE_BASE_DIR}/DolbyVision
    create_directory ${RESOLVE_BASE_DIR}/Fairlight
    create_directory ${RESOLVE_BASE_DIR}/Media
    create_directory ${RESOLVE_BASE_DIR}/"Resolve Disk Database"

    # Copy objects
    copy_object ${UNPACK_DIR}/bin ${RESOLVE_BASE_DIR}
    copy_object ${UNPACK_DIR}/Control ${RESOLVE_BASE_DIR}
    copy_object ${UNPACK_DIR}/DaVinci\ Resolve\ Panels\ Setup ${RESOLVE_BASE_DIR}
    copy_object ${UNPACK_DIR}/Developer ${RESOLVE_BASE_DIR}
    copy_object ${UNPACK_DIR}/docs ${RESOLVE_BASE_DIR}
    copy_object ${UNPACK_DIR}/Fusion ${RESOLVE_BASE_DIR}
    copy_object ${UNPACK_DIR}/graphics ${RESOLVE_BASE_DIR}
    copy_object ${UNPACK_DIR}/libs ${RESOLVE_BASE_DIR}
    copy_object ${UNPACK_DIR}/LUT ${RESOLVE_BASE_DIR}
    copy_object ${UNPACK_DIR}/Onboarding ${RESOLVE_BASE_DIR}
    copy_object ${UNPACK_DIR}/plugins ${RESOLVE_BASE_DIR}
    copy_object ${UNPACK_DIR}/UI_Resource ${RESOLVE_BASE_DIR}
    copy_object ${UNPACK_DIR}/scripts/script.checkfirmware ${RESOLVE_BASE_DIR}/scripts/
    copy_object ${UNPACK_DIR}/scripts/script.getlogs.v4 ${RESOLVE_BASE_DIR}/scripts/
    copy_object ${UNPACK_DIR}/scripts/script.start ${RESOLVE_BASE_DIR}/scripts/
    copy_object ${UNPACK_DIR}/share/default-config-linux.dat ${RESOLVE_BASE_DIR}/configs/config.dat-pkg-default
    copy_object ${UNPACK_DIR}/share/log-conf.xml ${RESOLVE_BASE_DIR}/configs/log-conf.xml-pkg-default
    copy_object ${UNPACK_DIR}/share/default_cm_config.bin ${RESOLVE_BASE_DIR}/DolbyVision/config.bin-pkg-default
    copy_object ${UNPACK_DIR}/libs/libBlackmagicRawAPI.so ${RESOLVE_BASE_DIR}/bin/

    # Install panel API library
    create_directory ${DEB_DIR}/usr/lib/
    extract_tgz ${UNPACK_DIR}/share/panels/dvpanel-framework-linux-x86_64.tgz ${DEB_DIR}/usr/lib/ libDaVinciPanelAPI.so

    # Create udev rules
    create_directory ${DEB_DIR}/lib/udev/rules.d
    cat > ${DEB_DIR}/lib/udev/rules.d/75-davincipanel.rules <<EOF
SUBSYSTEM=="usb", ATTRS{idVendor}=="1edb", MODE="0666"
EOF
    cat > ${DEB_DIR}/lib/udev/rules.d/75-sdx.rules <<EOF
SUBSYSTEM=="usb", ENV{DEVTYPE}=="usb_device", ATTRS{idVendor}=="096e", MODE="0666"
EOF

    # Create desktop shortcuts
    assert_object ${DEB_DIR}/opt/resolve/graphics/DV_Resolve.png
    cat > ${DEB_DIR}/usr/share/applications/${DEB_NAME}.desktop <<EOF
[Desktop Entry]
Version=1.0
Encoding=UTF-8
Exec=/opt/resolve/bin/resolve
Icon=/opt/resolve/graphics/DV_Resolve.png
Name=${RESOLVE_NAME}
Terminal=false
MimeType=application/x-resolveproj;
Type=Application
StartupNotify=true
Categories=AudioVideo
EOF
    assert_object ${DEB_DIR}/opt/resolve/graphics/DV_Panels.png
    cat > ${DEB_DIR}/usr/share/applications/${DEB_NAME}-panel-setup.desktop <<EOF
[Desktop Entry]
Version=1.0
Encoding=UTF-8
Exec="/opt/resolve/DaVinci Resolve Panels Setup/DaVinci Resolve Panels Setup"
Icon=/opt/resolve/graphics/DV_Panels.png
Name=DaVinci Resolve Panels Setup
Terminal=false
Type=Application
StartupNotify=true
Categories=AudioVideo
EOF

    # Add postinst commands
    cat >> ${DEB_DIR}/DEBIAN/postinst <<EOF
test -e /opt/resolve/configs/config.dat || cp /opt/resolve/configs/config.dat-pkg-default /opt/resolve/configs/config.dat
test -e /opt/resolve/configs/log-conf.xml || cp /opt/resolve/configs/log-conf.xml-pkg-default /opt/resolve/configs/log-conf.xml
test -e /opt/resolve/DolbyVision/config.bin || cp /opt/resolve/DolbyVision/config.bin-pkg-default /opt/resolve/DolbyVision/config.bin
chmod -R a+rw /opt/resolve/configs
chmod -R a+rw /opt/resolve/easyDCP
chmod -R a+rw /opt/resolve/logs
chmod -R a+rw /opt/resolve/Developer
chmod -R a+rw /opt/resolve/DolbyVision
chmod -R a+rw /opt/resolve/LUT
chmod -R a+rw /opt/resolve/.LUT
chmod -R a+rw /opt/resolve/.license
chmod -R a+rw /opt/resolve/.crashreport
chmod -R a+rw /opt/resolve/"Resolve Disk Database"
chmod -R a+rw /opt/resolve/Fairlight
chmod -R a+rw /opt/resolve/Media
EOF
}

process16() {
    # Create directories
    create_directory ${RESOLVE_BASE_DIR}/easyDCP
    create_directory ${RESOLVE_BASE_DIR}/scripts
    create_directory ${RESOLVE_BASE_DIR}/.license
    create_directory ${RESOLVE_BASE_DIR}/share
    create_directory ${RESOLVE_BASE_DIR}/Fairlight

    # Copy objects
    copy_object ${UNPACK_DIR}/bin ${RESOLVE_BASE_DIR}
    copy_object ${UNPACK_DIR}/Control ${RESOLVE_BASE_DIR}
    copy_object ${UNPACK_DIR}/DaVinci\ Resolve\ Panels\ Setup ${RESOLVE_BASE_DIR}
    copy_object ${UNPACK_DIR}/Developer ${RESOLVE_BASE_DIR}
    copy_object ${UNPACK_DIR}/docs ${RESOLVE_BASE_DIR}
    copy_object ${UNPACK_DIR}/Fusion ${RESOLVE_BASE_DIR}
    copy_object ${UNPACK_DIR}/graphics ${RESOLVE_BASE_DIR}
    copy_object ${UNPACK_DIR}/libs ${RESOLVE_BASE_DIR}
    copy_object ${UNPACK_DIR}/LUT ${RESOLVE_BASE_DIR}
    copy_object ${UNPACK_DIR}/Onboarding ${RESOLVE_BASE_DIR}
    copy_object ${UNPACK_DIR}/plugins ${RESOLVE_BASE_DIR}
    if ! [[ "$RESOLVE_VERSION" == 16.0b* ]];
    then
	copy_object ${UNPACK_DIR}/Technical\ Documentation ${RESOLVE_BASE_DIR}
    fi
    copy_object ${UNPACK_DIR}/UI_Resource ${RESOLVE_BASE_DIR}
    copy_object ${UNPACK_DIR}/scripts/script.checkfirmware ${RESOLVE_BASE_DIR}/scripts/
    copy_object ${UNPACK_DIR}/scripts/script.getlogs.v4 ${RESOLVE_BASE_DIR}/scripts/
    copy_object ${UNPACK_DIR}/scripts/script.start ${RESOLVE_BASE_DIR}/scripts/
    copy_object ${UNPACK_DIR}/share/default-config.dat ${RESOLVE_BASE_DIR}/share/
    copy_object ${UNPACK_DIR}/share/log-conf.xml ${RESOLVE_BASE_DIR}/share/
    copy_object ${UNPACK_DIR}/share/default_cm_config.bin ${RESOLVE_BASE_DIR}/share/

    # Extract panel API library
    create_directory ${DEB_DIR}/usr/lib
    extract_tgz ${UNPACK_DIR}/share/panels/dvpanel-framework-linux-x86_64.tgz ${DEB_DIR}/usr/lib libDaVinciPanelAPI.so

    # Create symlinks
    create_directory ${RESOLVE_BASE_DIR}/bin/BlackmagicRawAPI/
    link_object /opt/resolve/libs/libBlackmagicRawAPI.so ${RESOLVE_BASE_DIR}/bin/libBlackmagicRawAPI.so
    link_object /opt/resolve/libs/libBlackmagicRawAPI.so ${RESOLVE_BASE_DIR}/bin/BlackmagicRawAPI/libBlackmagicRawAPI.so

    # Create common data dir
    create_directory ${DEB_DIR}/var/BlackmagicDesign/DaVinci\ Resolve

    # Create udev rules
    create_directory ${DEB_DIR}/lib/udev/rules.d
    cat > ${DEB_DIR}/lib/udev/rules.d/75-davincipanel.rules <<EOF
SUBSYSTEM=="usb", ATTRS{idVendor}=="1edb", MODE="0666"
EOF
    cat > ${DEB_DIR}/lib/udev/rules.d/75-sdx.rules <<EOF
SUBSYSTEM=="usb", ENV{DEVTYPE}=="usb_device", ATTRS{idVendor}=="096e", MODE="0666"
EOF

    # Create desktop shortcuts
    assert_object ${DEB_DIR}/opt/resolve/graphics/DV_Resolve.png
    cat > ${DEB_DIR}/usr/share/applications/${DEB_NAME}.desktop <<EOF
[Desktop Entry]
Version=1.0
Encoding=UTF-8
Exec=/opt/resolve/bin/resolve
Icon=/opt/resolve/graphics/DV_Resolve.png
Name=${RESOLVE_NAME}
Terminal=false
MimeType=application/x-resolveproj;
Type=Application
StartupNotify=true
Categories=AudioVideo
EOF
    assert_object ${DEB_DIR}/opt/resolve/graphics/DV_Panels.png
    cat > ${DEB_DIR}/usr/share/applications/${DEB_NAME}-panel-setup.desktop <<EOF
[Desktop Entry]
Version=1.0
Encoding=UTF-8
Exec="/opt/resolve/DaVinci Resolve Panels Setup/DaVinci Resolve Panels Setup"
Icon=/opt/resolve/graphics/DV_Panels.png
Name=DaVinci Resolve Panels Setup
Terminal=false
Type=Application
StartupNotify=true
Categories=AudioVideo
EOF

    # Add postinst commands
    cat >> ${DEB_DIR}/DEBIAN/postinst <<EOF
chmod -R a+rw /opt/resolve/easyDCP
chmod -R a+rw /opt/resolve/LUT
chmod -R a+rw /opt/resolve/.license
chmod -R a+rw /opt/resolve/Fairlight
chmod -R a+rw /var/BlackmagicDesign/"DaVinci Resolve"
EOF
    
    # libcudafix for Resolve 16.0 & 16.1
    if [[ "$RESOLVE_VERSION" == 16.0* ]] || [[ "$RESOLVE_VERSION" == 16.1* ]];
    then
	echo "Implementing libcudafix"
	echo "test ! -e /usr/lib64 && mkdir /usr/lib64 && touch /usr/lib64.by.makeresolvedeb" >> ${DEB_DIR}/DEBIAN/postinst
	echo "test ! -h /usr/lib64/libcuda.so && ln -s /usr/lib/x86_64-linux-gnu/libcuda.so /usr/lib64/libcuda.so && touch /usr/lib64/libcuda.so.by.makeresolvedeb" >> ${DEB_DIR}/DEBIAN/postinst
	echo "test -e /usr/lib64/libcuda.so.by.makeresolvedeb && rm /usr/lib64/libcuda.so && rm /usr/lib64/libcuda.so.by.makeresolvedeb" >> ${DEB_DIR}/DEBIAN/postrm
	echo "test -e /usr/lib64.by.makeresolvedeb && rmdir /usr/lib64 && rm /usr/lib64.by.makeresolvedeb" >> ${DEB_DIR}/DEBIAN/postrm
    fi
}

process17() {
    # Create directories
    create_directory ${RESOLVE_BASE_DIR}/easyDCP
    create_directory ${RESOLVE_BASE_DIR}/scripts
    create_directory ${RESOLVE_BASE_DIR}/.license
    create_directory ${RESOLVE_BASE_DIR}/share
    create_directory ${RESOLVE_BASE_DIR}/Fairlight

    # Copy objects
    copy_object ${UNPACK_DIR}/bin ${RESOLVE_BASE_DIR}
    copy_object ${UNPACK_DIR}/Control ${RESOLVE_BASE_DIR}
    copy_object ${UNPACK_DIR}/DaVinci\ Control\ Panels\ Setup ${RESOLVE_BASE_DIR}
    copy_object ${UNPACK_DIR}/Developer ${RESOLVE_BASE_DIR}
    copy_object ${UNPACK_DIR}/docs ${RESOLVE_BASE_DIR}
    copy_object ${UNPACK_DIR}/Fusion ${RESOLVE_BASE_DIR}
    copy_object ${UNPACK_DIR}/graphics ${RESOLVE_BASE_DIR}
    copy_object ${UNPACK_DIR}/libs ${RESOLVE_BASE_DIR}
    copy_object ${UNPACK_DIR}/LUT ${RESOLVE_BASE_DIR}
    copy_object ${UNPACK_DIR}/Onboarding ${RESOLVE_BASE_DIR}
    copy_object ${UNPACK_DIR}/plugins ${RESOLVE_BASE_DIR}
    if ! [[ "$RESOLVE_VERSION" == 16.0b* ]];
    then
	copy_object ${UNPACK_DIR}/Technical\ Documentation ${RESOLVE_BASE_DIR}
    fi
    copy_object ${UNPACK_DIR}/UI_Resource ${RESOLVE_BASE_DIR}
    copy_object ${UNPACK_DIR}/scripts/script.checkfirmware ${RESOLVE_BASE_DIR}/scripts/
    copy_object ${UNPACK_DIR}/scripts/script.getlogs.v4 ${RESOLVE_BASE_DIR}/scripts/
    copy_object ${UNPACK_DIR}/scripts/script.start ${RESOLVE_BASE_DIR}/scripts/
    copy_object ${UNPACK_DIR}/share/default-config.dat ${RESOLVE_BASE_DIR}/share/
    copy_object ${UNPACK_DIR}/share/log-conf.xml ${RESOLVE_BASE_DIR}/share/
    copy_object ${UNPACK_DIR}/share/default_cm_config.bin ${RESOLVE_BASE_DIR}/share/

    # Extract panel API library
    create_directory ${DEB_DIR}/usr/lib
    extract_tgz ${UNPACK_DIR}/share/panels/dvpanel-framework-linux-x86_64.tgz ${DEB_DIR}/usr/lib libDaVinciPanelAPI.so

    # Create symlinks
    create_directory ${RESOLVE_BASE_DIR}/bin/BlackmagicRawAPI/
    link_object /opt/resolve/libs/libBlackmagicRawAPI.so ${RESOLVE_BASE_DIR}/bin/libBlackmagicRawAPI.so
    link_object /opt/resolve/libs/libBlackmagicRawAPI.so ${RESOLVE_BASE_DIR}/bin/BlackmagicRawAPI/libBlackmagicRawAPI.so

    # Create common data dir
    create_directory ${DEB_DIR}/var/BlackmagicDesign/DaVinci\ Resolve

    # Create udev rules
    create_directory ${DEB_DIR}/lib/udev/rules.d
    cat > ${DEB_DIR}/lib/udev/rules.d/75-davincipanel.rules <<EOF
SUBSYSTEM=="usb", ATTRS{idVendor}=="1edb", MODE="0666"
EOF
    cat > ${DEB_DIR}/lib/udev/rules.d/75-davincikb.rules <<EOF
SUBSYSTEMS=="usb", ENV{.LOCAL_ifNum}="$attr{bInterfaceNumber}"
# Editor Keyboard
SUBSYSTEM=="hidraw", KERNEL=="hidraw*", ATTRS{idVendor}=="1edb", ATTRS{idProduct}=="da0b", ENV{.LOCAL_ifNum}=="04", MODE="0666"
# Speed Editor Keyboard
SUBSYSTEM=="hidraw", KERNEL=="hidraw*", ATTRS{idVendor}=="1edb", ATTRS{idProduct}=="da0e", ENV{.LOCAL_ifNum}=="02", MODE="0666"
EOF
    cat > ${DEB_DIR}/lib/udev/rules.d/75-sdx.rules <<EOF
SUBSYSTEM=="usb", ENV{DEVTYPE}=="usb_device", ATTRS{idVendor}=="096e", MODE="0666"
EOF

    # Create desktop shortcuts
    assert_object ${DEB_DIR}/opt/resolve/graphics/DV_Resolve.png
    cat > ${DEB_DIR}/usr/share/applications/${DEB_NAME}.desktop <<EOF
[Desktop Entry]
Version=1.0
Encoding=UTF-8
Exec=/opt/resolve/bin/resolve
Icon=/opt/resolve/graphics/DV_Resolve.png
Name=${RESOLVE_NAME}
Terminal=false
MimeType=application/x-resolveproj;
Type=Application
StartupNotify=true
Categories=AudioVideo
EOF
    assert_object ${DEB_DIR}/opt/resolve/graphics/DV_Panels.png
    cat > ${DEB_DIR}/usr/share/applications/${DEB_NAME}-panel-setup.desktop <<EOF
[Desktop Entry]
Version=1.0
Encoding=UTF-8
Exec="/opt/resolve/DaVinci Control Panels Setup/DaVinci Control Panels Setup"
Icon=/opt/resolve/graphics/DV_Panels.png
Name=DaVinci Control Panels Setup
Terminal=false
Type=Application
StartupNotify=true
Categories=AudioVideo
EOF

    # Add postinst commands
    cat >> ${DEB_DIR}/DEBIAN/postinst <<EOF
chmod -R a+rw /opt/resolve/easyDCP
chmod -R a+rw /opt/resolve/LUT
chmod -R a+rw /opt/resolve/.license
chmod -R a+rw /opt/resolve/Fairlight
chmod -R a+rw /var/BlackmagicDesign/"DaVinci Resolve"
EOF
}

process1617braw() {
    if ! [[ -e ${UNPACK_DIR}/BlackmagicRAWPlayer ]]; then
	return;
    fi
    echo "Adding BlackmagicRAWPlayer"

    copy_object ${UNPACK_DIR}/BlackmagicRAWPlayer ${RESOLVE_BASE_DIR}

    assert_object ${DEB_DIR}/opt/resolve/graphics/blackmagicraw-player_256x256_apps.png
    assert_object ${DEB_DIR}/opt/resolve/BlackmagicRAWPlayer/BlackmagicRAWPlayer
    cat > ${DEB_DIR}/usr/share/applications/${DEB_NAME}-braw-player.desktop <<EOF
[Desktop Entry]
Version=1.0
Encoding=UTF-8
Exec=/opt/resolve/BlackmagicRAWPlayer/BlackmagicRAWPlayer
Icon=/opt/resolve/graphics/blackmagicraw-player_256x256_apps.png
Name=Blackmagic RAW Player
Terminal=false
MimeType=application/x-braw-clip;application/x-braw-sidecar
Type=Application
StartupNotify=true
Categories=AudioVideo
EOF

    if ! [[ -e ${UNPACK_DIR}/BlackmagicRAWSpeedTest ]]; then
	return;
    fi
    echo "Adding BlackmagicRAWSpeedTest"

    copy_object ${UNPACK_DIR}/BlackmagicRAWSpeedTest ${RESOLVE_BASE_DIR}

    assert_object ${DEB_DIR}/opt/resolve/graphics/blackmagicraw-speedtest_256x256_apps.png
    assert_object ${DEB_DIR}/opt/resolve/BlackmagicRAWSpeedTest/BlackmagicRAWSpeedTest
    cat > ${DEB_DIR}/usr/share/applications/${DEB_NAME}-braw-speedtest.desktop <<EOF
[Desktop Entry]
Version=1.0
Encoding=UTF-8
Exec=/opt/resolve/BlackmagicRAWSpeedTest/BlackmagicRAWSpeedTest
Icon=/opt/resolve/graphics/blackmagicraw-speedtest_256x256_apps.png
Name=Blackmagic RAW Speed Test
Terminal=false
Type=Application
StartupNotify=true
Categories=AudioVideo
EOF
}

installer_extract_xorriso() {
    # Extract archive
    check_command xorriso
    echo "Extracting archive"
    createf_directory ${UNPACK_DIR}
    xorriso -osirrox on -indev ${INSTALLER_ARCHIVE} -extract / ${UNPACK_DIR}
    if [[ -z "$(ls -A ${UNPACK_DIR})" ]];
    then
	echo "[ERROR] Failed to extract DaVinci Resolve archive"
	remove_directory ${UNPACK_DIR}
	exit 1
    fi
}

installer_extract_native() {
    # Extract archive
    echo "Extracting archive"
    createf_directory ${UNPACK_DIR}
    ./${INSTALLER_ARCHIVE} -i -y -n -C ${UNPACK_DIR} >/dev/null
    if [[ -z "$(ls -A ${UNPACK_DIR})" ]];
    then
	echo "[ERROR] Failed to extract DaVinci Resolve archive"
	remove_directory ${UNPACK_DIR}
	exit 1
    fi
}

echo "MakeResolveDeb ${MAKERESOLVEDEB_VERSION}"

# Check argument
case $1 in
    *.run)
	INSTALLER_ARCHIVE=$1
	FILENAMEP1=$(echo $INSTALLER_ARCHIVE | cut -d'_' -f1 -)
	FILENAMEP2=$(echo $INSTALLER_ARCHIVE | cut -d'_' -f2 -)
	FILENAMEP3=$(echo $INSTALLER_ARCHIVE | cut -d'_' -f3 -)
	FILENAMEP4=$(echo $INSTALLER_ARCHIVE | cut -d'_' -f4 -)
	FILENAMEP5=$(echo $INSTALLER_ARCHIVE | cut -d'_' -f5 -)
	;;
    *)
	echo "Usage: $0 <DaVinci_Resolve_*_Linux.run>"
	exit 1
	;;
esac

# Check if file exists
if [[ ! -e $INSTALLER_ARCHIVE ]];
then
    echo "[ERROR] File does not exist"
    exit 1
fi

# Validate and parse archive name
if [[ "$FILENAMEP1" != "DaVinci" ]] || [[ "$FILENAMEP2" != "Resolve" ]];
then
    echo "[ERROR] File does not look like a valid DaVinci Resolve installer archive"
    exit 1
fi
if [[ "$FILENAMEP5" == "Linux.run" ]] && [[ "$FILENAMEP3" == "Studio" ]];
then
    RESOLVE_NAME="DaVinci Resolve Studio"
    RESOLVE_VERSION=$FILENAMEP4
    DEB_NAME=davinci-resolve-studio
    DEB_CONFLICTS=davinci-resolve
elif [[ "$FILENAMEP4" == "Linux.run" ]];
then
    RESOLVE_NAME="DaVinci Resolve"
    RESOLVE_VERSION=$FILENAMEP3
    DEB_NAME=davinci-resolve
    DEB_CONFLICTS=davinci-resolve-studio
else
    echo "[ERROR] File does not look like a valid DaVinci Resolve installer archive"
    exit 1
fi
UNPACK_DIR=./unpack-${DEB_NAME}-${RESOLVE_VERSION}
DEB_VERSION=${RESOLVE_VERSION}-mrd${MAKERESOLVEDEB_VERSION}
DEB_DIR=./${DEB_NAME}_${DEB_VERSION}_amd64
RESOLVE_BASE_DIR=${DEB_DIR}/opt/resolve
ERRORS=0

echo
echo "Detected ${RESOLVE_NAME} version ${RESOLVE_VERSION}"
echo

# Verify that we have the commands we need
check_command tar
check_command fakeroot
check_command dpkg-deb
echo

# Create destination directories
createf_directory ${DEB_DIR}
createf_directory ${RESOLVE_BASE_DIR}

# Initialize Debian package structure
init_deb

# Determine which conversion processs to use
case $RESOLVE_VERSION in
    15.*)
	echo "Using Resolve 15 conversion process"
	installer_extract_xorriso
	process15
	;;
    16.*)
	echo "Using Resolve 16 conversion process"
	installer_extract_native
	process16
	process1617braw
	;;
    17.*)
	echo "Using Resolve 17 conversion process"
	installer_extract_native
	process17
	process1617braw
	;;
    *)
	echo "Unknown Resolve version"
	echo "Trying Resolve 17 conversion process"
	installer_extract_native
	process17
	process1617braw
	;;
esac

# Create Debian package
close_deb
echo "Creating Debian package"
if ! fakeroot dpkg-deb -b ${DEB_DIR} ${DEB_DIR}.deb;
then
    ERRORS=$((ERRORS+1))
fi

# Clean up
remove_directory ${UNPACK_DIR}
remove_directory ${DEB_DIR}

# Report
echo
echo "[DONE] errors reported ${ERRORS}"
echo

exit $ERRORS
