#!/bin/bash

HTTP_STATUS=200

copy_files() {
  APP_NAME=$(basename `dirname $0`)
  file="/home/$APP_NAME/files/updateableAssetsInventory";
  if [ -f "$file" ]; then
    tr -s " " < $file
    while IFS= read -r line; do
      set -- $line;
      srcfile=$(echo "/home/$APP_NAME/$1" | sed -e 's/\r//g'); # remove new lines
      dstfile=$(echo "/home/$APP_NAME/$2" | sed -e 's/\r//g'); # remove new lines
      if [ -f "$srcfile" ]; then # if file that has to be copied exists
      dstdir=${dstfile%/*};
        if [ -d "$dstdir" ]; then # if dir where file has to be copied exists
          cp -r "$srcfile" "$dstfile";
        else # dir does not exist
          HTTP_STATUS=404;
          ERROR_MESSAGE="Cannot copy '$srcfile' to '$dstdir' directory does not exist";
          return 3;  
        fi
      else # file does not exist
        HTTP_STATUS=404;
        ERROR_MESSAGE="File '$srcfile' does not exist";
        return 2;
      fi
    done <"$file";
  else  # file updateableAssetsInventory does not exist
    HTTP_STATUS=404;
    ERROR_MESSAGE="File '$file' does not exist";
    return 1;
  fi
  return 0;
}

copy_files
STATUS_CODE=$?
echo "Status: $HTTP_STATUS"
echo "Content-type: application/json"
echo ""
if [ "$STATUS_CODE" -ne 0 ]
then
  echo "{\"errorCode\": \"$STATUS_CODE\", \"errorMessage\": \"$ERROR_MESSAGE\"}"
else
  echo "{\"status\": \"0\"}"
fi