#!/bin/bash

# import.sh
# converting levelsets and single levels to packages

function import_select () {
  get_val " File/directory to import:"
  import_file $tmp
}

function import () {
  local file="$1"; import_group="$2"; import_name="${3:-${1##*/}}"
  header
  echo " ## Importing '$file'"
  if [ ! -e "$file" ]; then
    echo " ## Failed: $file: No such file or directory."
    return_to_main_menu && return
  fi
  if [ "${file:(-4)}" == ".zip" ]; then
    import_zip $file
  elif [ "${file:(-6)}" == ".level" ]; then
    import_single $file
  elif [ -d "$file" ]
    import_levelset $file
  else
    echo " ## Failed: unknown type of $import_name"
    return_to_main_menu && return
  fi
}

function import_zip () {
  # remove old zipdir
  [ -d $tmp_dir/zipdir ] && rm -r $tmp_dir/zipdir
  
  unzip $file -d $tmp_dir/zipdir
  returncode=$?
  if ( [ -n "$returncode" ] && [ "$returncode" -gt 0 ] ); then
    echo " ## Failed: 'unzip' failed; .zip file maybe broken"
    return_to_main_menu && return
  fi
  
  # remove Readme.txt from files downloaded from www.bd-fans.com which were originally hosted by www.zomis.net
  [ -f "$tmp_dir/zipdir/Readme.txt" -a ! -f "$tmp_dir/zipdir/levelinfo.conf" ] && rm $tmp_dir/zipdir/Readme.txt
  
  if [ -z "`find $tmp_dir/zipdir -name "*.level"`" ]; then
    # it is not a levelset at all
    echo " ## Failed: no levels found in the archive"
    return_to_main_menu && return
  fi
  
  if [ -f "$tmp_dir/zipdir/levelinfo.conf" ]; then
    # it is a levelset which isn't in its own directory
    local tmp=${1##*/}
    tmp=$tmp_dir/zipdir/${tmp%.zip}
    mkdir $tmp
    find $tmp_dir/zipdir -type f -exec mv {} $tmp \;
  fi
  
  import_levelset "`find $tmp_dir/zipdir -mindepth 1 -type d | sed 1q`"
}

function import_single () {
  get_val -n " Level name:"
  import_name=$tmp
}


