#!/bin/bash
if [ $# -eq 0 ]
then
  echo "No output package name given!"
  exit 1
fi

output=$1

if [[ ! "$output" =~ ^[a-z.A-Z0-9_-]{1,}$ ]]; then
  echo "Invalid output name! The name must only contain letters, numbers, hyphens or underscores!"
  exit 1
fi

type="binary"
toCompress=("pkg.info")

echo "Creating package with the name $output..."

if [ -d files ]; then
  echo "files/ directory found"
  toCompress+=("files/")
else
  if [ -f source.sh ]; then
    type="source"
    echo "source.sh file found"
    toCompress+=("source.sh")
    if [ -f pre_update.sh ]; then
      echo "pre_update.sh file found"
      toCompress+=("pre_update.sh")
    fi
    if [ -f post_update.sh ]; then
      echo "post_update.sh file found"
      toCompress+=("post_update.sh")
    fi
    if [ -f pre_install.sh ]; then
      echo "pre_install.sh file found"
      toCompress+=("pre_install.sh")
    fi
    if [ -f post_install.sh ]; then
      echo "post_install.sh file found"
      toCompress+=("post_install.sh")
    fi
    if [ -f post_remove.sh ]; then
          echo "post_remove.sh file found"
          toCompress+=("post_remove.sh")
        fi
    if [ -d source-files ]; then
      if [ ! -z "$(ls -A source-files)" ]; then
        echo "source-files/ directory found"
        toCompress+=("source-files/")
      fi
    fi
  else
    echo "files/ directory or source.sh file not found in $PWD"
    exit 1
  fi
fi

if [ -f pkg.info ]; then
  echo "pkg.info file found"
else
  echo "pkg.info file not found in $PWD"
  exit 1
fi

echo "Creating $type package as $output"

tar -czf "$output" "${toCompress[@]}"
