#!/usr/bin/env bash
# Usage: cdz [--check] <archive>

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

is_archive()
{
  local file="$1"
  local mime_type=$(file --mime-type -b "$file")

  if [[ $mime_type == *"tar"* || $file == *.tar* || \
        $mime_type == "application/zip" || $mime_type == "application/x-rar" ]]
  then
    return 0
  fi

  if command -v archivemount >/dev/null 2>&1
  then
    local test_dir=$(mktemp -d /tmp/cdz_check.XXXXXXXX)
    local result=1
    if archivemount -o readonly "$file" "$test_dir" >/dev/null 2>&1
    then
      result=0
      umount "$test_dir"
    fi
    rmdir "$test_dir"
    return $result
  fi

  return 1
}

check_mode=0
if [[ "$1" == "--check" ]]
then
  check_mode=1
  shift
fi

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

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

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

if is_archive "$target_abs"
then
  if [[ $check_mode -eq 1 ]]
  then
    exit 0
  fi
else
  if [[ $check_mode -eq 1 ]]
  then
    exit 1
  fi
  mime_type=$(file --mime-type -b "$target_abs")
  echo "Unsupported archive type: $mime_type"
  exit 1
fi

# Proceed with extraction
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_abs")
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_abs == *.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"
