#!/usr/bin/env bash


# Initialize empty variable
# This should be the full path to the tar.gz compile package
package=''

# Argument parsing
# Note: If a character is followed by a colon (e.g. s:), that option is expected to have an argument

while getopts 'p:' flag; do
  case "${flag}" in
    p) package="${OPTARG}" ;;
    *) exit 1;;
  esac
done

if [ -z "${package}" ]
then
  echo "Please specify a package to download"
  exit
fi

# Standard function to exit with a failing return code
error_exit () {
  echo "${1}" >&2
  exit 1
}

# Get the file name from the full package path
regex='.*\/(.*)$'
if [[ ${package} =~ ${regex} ]]
then
  filename="${BASH_REMATCH[1]}"
fi

# Copy the package locally
cp $package /tmp/ || error_exit "Error copying compile package"

# Extract the package into the container's /pkg/qct/qctss/linux/bin directory
tar -zxvf /tmp/$filename --directory /pkg/qct/qctss/linux/bin/ --strip-components=2 || error_exit "Error extracting compile package"
