#!/usr/bin/env bash
# Usage: cdz <archive>

if [[ $LD_INTERNAL -ne 1 ]]; then
  LD_INTERNAL=1
  . $(dirname $(realpath $0))/daisy.source
fi

target=$1
if [[ -z "$target" ]]; then
  echo "No target specified."
  exit 1
fi

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

target_abs=$(realpath "$target")
name=$(basename "$target")

has_archivemount=$(command -v archivemount >/dev/null 2>&1; echo $?)

if [[ $has_archivemount -eq 0 && $NO_ARCHIVEMOUNT -ne 1 ]]; then
  use_mounter=1
else
  use_mounter=0
fi

mime_type=$(file --mime-type -b "$target")

comm1=(:)
comm2=(echo "Unsupported archive type: $mime_type")
comm3=(:)
comm4=(:)
comm5=(:)

if [[ $use_mounter -eq 1 ]]; then
  echo "Using archivemount..."
  comm2=(archivemount -o allow_root,use_ino "$target_abs")
  comm4=(cd ..)
  comm5=(umount)
elif [[ $mime_type == *"tar"* || $target == *.tar* ]]; then
  comm2=(tar xvf "$target_abs" -C)
elif [[ $mime_type == "application/zip" ]]; then
  if command -v unzip >/dev/null 2>&1; then
    comm2=(unzip -q "$target_abs" -d)
  else
    comm1=(echo "unzip is missing")
    comm3=(exit 1)
  fi
elif [[ $mime_type == "application/x-rar" ]]; then
  if command -v unrar >/dev/null 2>&1; then
    # unrar needs the directory as the last argument
    comm2=(unrar x -idq "$target_abs")
  else
    comm1=(echo "unrar is missing")
    comm3=(exit 1)
  fi
fi

dir=$(mktemp -d /tmp/extracted.XXXXXXXX)

"${comm1[@]}"
if [[ ${comm2[0]} == "unrar" ]]; then
  "${comm2[@]}" "$dir"
else
  "${comm2[@]}" "$dir"
fi
"${comm3[@]}"

sym="$(pwd)/$name.tmp"
ln -sf "$dir" "$sym"
cd "$sym"

echo "Extracted to $dir (linked via $sym)"
echo "Type exit to finish."

eval $SHELL

"${comm4[@]}"
"${comm5[@]}" "$dir"
rm -rf "$dir"
rm "$sym"
