#!/bin/bash
PS4='\e[1;34m+ ${LINENO}:\e[0m '
path=$2
type rename
echo -e "\e[38;2;0;255;100m"'$1 = '"$1""\n"'$2 = '"$2""\n"'$3 = '"$3""\n"
if [[ $? != 0 ]]; then
  echo -e "\e[38;2;255;0;100m""install rename" && exit
fi
help_message(){
echo -e "\e[38;2;250;255;0m"'$1 = index, unindex or organise'
echo -e "\e[38;2;250;255;0m"'$2 = path'
echo -e "\e[38;2;250;255;0m"'$3 = set as test to do a dry run of unindex or organise. or set as hashlist.txt location for indexing'"\n"
echo -e "\e[38;2;250;255;0m""adding a DO_NOT_INDEX file to a directory will stop this script from indexing it"
echo -e "\e[38;2;250;255;0m""adding a desc.txt file in a directory will add a descripion into the html"
exit
}

if [[ -z $1 ]]; then
  help_message
  elif [[ -z $2 ]]; then
  help_message
fi
if [[ $2 == *" "* ]]; then
  echo -e "\e[38;2;255;0;0m""given path contains spaces" && exit
elif [[ ! -d $2 ]]; then
  echo -e "\e[38;2;255;0;0m""given path $2 doesnt exist" && exit
fi

dry_run=false
case "$3" in
  "test")
   dry_run=true && echo -e "\e[38;2;0;255;0m"'dry_run=true'"\e[0m"
   ;;
   "")
   echo '$3' empty
   hashlist=/dev/null
   ;;
  *)
  if [ $1 == index ]; then
    if [[ $3 == *hashlist.txt ]]; then
      hashlist=$3
    else
      echo '$3 != "*hashlist.txt"' && help_message && exit
    fi
  else
    echo '$3' not recognised && help_message && exit
  fi
esac

if [[ "$(find $path)" == *" "* ]]; then
  echo -e "\e[38;2;250;255;0m""removing any spaces from file names and directories""\e[0m" && set -x
  find $path -exec rename 's/ /_/g' '{}' \;
fi
set -x
if [[ $1 == organise ]]; then
  dirs=$(find $path -type d)
  for dir in $dirs; do
    is_empty=$(ls -1A $dir | wc -l)
    if [[ $is_empty == 0 ]]; then
      echo -e "\e[38;2;100;255;0m""empty directory $dir found, removing""\e[0m"
      if [[ $dry_run == false ]]; then
        rmdir "$dir"
      fi
      continue
    fi
    file=$(ls -1AF $dir | grep -v / | tr -d '*')
    amount_of_files=$(ls -1AF $dir | grep -v / | wc -l)
    amount_of_dirs=$(ls -1AF $dir | grep / | wc -l)
    if [[ $amount_of_dirs == 0 ]] && [[ $amount_of_files == 1 ]]; then
      if [[ -e "$dir/../$file" ]]; then
        echo -e "\e[38;2;255;0;0m""$file exists in directory above $dir/..""\e[0m"
      else
        echo -e "\e[38;2;0;255;0m""$file doesnt exist in directory above $dir""\n moving $dir/$file to $(echo $dir | rev | cut -d '/' -f3- | rev)/$file""\n removing $dir""\e[0m"
        if [[ $dry_run == false ]]; then
          mv "$dir/$file" "$dir/../$file"
          rmdir "$dir"
        fi
      fi
    fi
  done
fi

if [[ $1 == index ]]; then
  if [[ -n $(find $path | grep DO_NOT_INDEX) ]]; then
    echo -e "\e[38;2;255;0;0m""DO_NOT_INDEX file found, exiting" && exit
  fi
  dirs=$(find $path -type d)
  for dir in $dirs ; do
   longest_name=$(ls -A $dir | awk '{ print length, $0 }' | sort -n | tail -n1 | cut -d ' ' -f1)
    > $dir/index.html
    a=$dir
    if [[ $dir == . ]];then
      a=/
    fi
    amount_files=$(ls -F1 $dir | grep -v index.html | grep -v / | wc -l)
    amount_dirs=$(ls -F1 $dir | grep  / | wc -l)
    f=files
    if [[ $amount_files == 1 ]];then
      f=file
    fi
    d=directories
    if [[ $amount_dirs == 1 ]]; then
      d=directory
    fi
    echo '<!DOCTYPE html>' >> $dir/index.html
    echo '<html>' >> $dir/index.html
    echo '<head>' >> $dir/index.html
    echo '<meta name="og:site_name" content="index of '$a'">' >> $dir/index.html
    echo '<meta property="og:description" content="'$amount_files $f' and '$amount_dirs $d'">' >> $dir/index.html
    echo '<meta name="theme-color" content="#00FF00">' >> $dir/index.html
    echo '<style>' >> $dir/index.html
    echo 'body {font-family: 'Courier New', Courier, monospace;}' >> $dir/index.html
    echo '.color { color: Lime; }' >> $dir/index.html
    echo '</style>' >> $dir/index.html
    echo '<title>index of '$dir'</title>' >> $dir/index.html
    echo '</head>' >> $dir/index.html
    echo '<body style="background-color:black;">' >> $dir/index.html
    echo '<h1 style="color:white">'"index of $dir"'</h1>' >> $dir/index.html
    if [[ -f $dir/desc.txt ]]; then
      echo '<h3 style="color:Gold">'"$(cat $dir/desc.txt)"'</h3>' >> $dir/index.html
    fi
    sub_dirs=$(ls -Fa $dir | grep '/$' | tr -d '*' | sort)
    echo "$dir"
    files=$(ls -Fa $dir | grep -v '/$' | tr -d '*' | sort)
      for sub_dir in $sub_dirs; do
        echo '<a class="color" href='$sub_dir'index.html>'$sub_dir'</a><br>' >> $dir/index.html
      done

     for file in $files; do
        if [[ $file == index.html ]]; then
          continue
        fi
          hash=
          is_in_hashlist=false
          needs_rehashing=true
        if [[ -n $(cat $hashlist | grep -w $(echo "$dir/$file" | tr -s '/')) ]]; then
          is_in_hashlist=true
          last_modified_in_list=$(cat $hashlist | sort | grep -w $(echo "$dir/$file" | tr -s '/') | head -n1| cut -d ' ' -f1)
        fi
        last_modified=$(stat -c %Y $dir/$file)
        if [[ $is_in_hashlist == true ]]; then
          echo last modified $last_modified last hashed $last_modified_in_list
          echo "$last_modified_in_list not greater than $last_modified?"
         if [[ ! $last_modified -gt $last_modified_in_list ]]; then
            echo -e "\e[38;2;0;255;50m""reusing hash for file $file""\e[0m"
            needs_rehashing=false
            echo $(cat $hashlist | sort | grep -w $(echo "$dir/$file" | tr -s '/') | head -n1)
            hash=$(echo "md5sum"'  '"$(cat $hashlist | sort | grep -w $(echo "$dir/$file" | tr -s '/') | head -n1 | cut -d ' ' -f5)")
          else
            echo -e "\e[38;2;200;255;0m""file $file isnt in hashlist or needs to be rehashed""\e[0m"
          fi
        fi

        name_lenght=$(echo $file | wc -c)
        offset=$(cat /dev/zero | head -c  $(($longest_name - $name_lenght + 4)) | tr '\0' '0' | sed 's/'"$(printf '0')"'/\&nbsp;/g')
        echo $offset
        echo -e "\e[38;2;0;255;0m""$dir""\e[0m"
        echo -e "\e[38;2;255;0;100m"$file"\e[0m"
        file_time=$(stat -c "%Y" "$dir"/"$file" | cut -d '.' -f1)
        size=$(echo $(echo $(du -h $dir/$file) | cut -d ' ' -f1)b | tr [:upper:] [:lower:] )
        if [[ ${#size} -eq 4 ]];then
          size+="&nbsp;"
        fi
        if [[ $needs_rehashing == true ]]; then
          hash=$(echo "md5sum"'  '"$(md5sum $dir/$file | cut -d ' ' -f1)")
          (stat -c "%Y %n" "$dir/$file" | tr '\n' ' ' ; echo "$hash") >> $hashlist
        fi

        echo '<a class="color"" href="'$file'"> '$file' </a><span style="color:white;"> '$offset $file_time $size $hash' </span>''<a class="color" href="'$file'" download>download</a><br>' >> $dir/index.html
      done
    echo '<br><br><p class="color">'indexed on $(date)'</p>' >> $dir/index.html
    echo '</body>' >> $dir/index.html
    echo '</html>' >> $dir/index.html
  done
fi

if [[ $1 == unindex ]]; then
  htmls=$(find $2 -type f -name index.html)
  if [[ -z $htmls ]];then
    echo -e "\e[38;2;255;0;100m""no index.html files found, exiting" && exit
  fi
  for html in $htmls ;do
    echo -e "\e[38;2;0;255;100m""removing $html""\e[0m"
    if [[ $dry_run == false ]]; then
      rm "$html"
    fi
  done
fi



