#!/bin/bash

if [[ $DAISY_INTERNAL -ne 1 ]];
then
  DAISY_INTERNAL=1 source $DAISY_SOURCE_FILE
fi

target=$1

# Check if file exists
if [[ -z "$target" ]];
then
  echo "No target specified."
  exit 1
fi

if ! test -f "$target";
then
  echo "File not found: \"$target\""
  exit 2
fi

file "$target" 1>/dev/null
exitcode=$?
report=$(file "$target")

# Check for archive type, supported types are zip/tar/rar
comm1=(:)
comm2=(echo "Unsupported archive type$add: \"$target\"")
comm3=(:)

echo $report | grep "tar archive" 1>/dev/null
istar=$?
echo $report | grep "Zip archive" 1>/dev/null
iszip=$?
echo $report | grep "Android" 1>/dev/null
iszip=$?
echo $report | grep "RAR archive" 1>/dev/null
israr=$?

# TAR archives come in many forms, if none of our tests say it's tar
# ...but it looks like tar and barks like tar, let's take the shot.
# Seems to work fairly well for the record.
RES=$(echo "$target" | grep ".tar")
if [[ $RES != "" ]];
then
  istar=0
fi

# Now we set the right command
if (( istar == 0 )); then
	comm2=(tar xvf "$target" -C)
elif (( iszip == 0 )); then
	which unzip 1>/dev/null
	exitcode=$?
	if (( exitcode == 0 )); then
		comm2=(unzip -q "$target" -d)
	else
		comm1=(echo "The utility 'unzip' is missing, please install it")
		comm3=(exit 1)
	fi
elif (( israr == 0 )); then
	which unrar 1>/dev/null
	exitcode=$?
	if (( exitcode == 0 )); then
		comm2=(unrar -i nul "$target")
	else
		comm1=(echo "The utility 'unrar' is missing, please install it")
		comm3=(exit 1)
	fi
fi

# Create the temp dir, usually
dir=$(mktemp -d /tmp/extracted.XXXXXXXX)

# And the rest of the commands
"${comm1[@]}"
"${comm2[@]}" $dir
"${comm3[@]}"

currentpath=$(realpath .)
cd $dir
ln -s $currentpath ./link-back
echo "A symlink to your original path has been created under the name \`link-back\`."
echo "You can use this to copy out files, but you can also just access your filesystem regularly."
echo "Type 'exit' to exit the extracted archive's folder and auto-delete it."
eval $SHELL
rm -rf $dir
