#!/bin/bash
### BEGIN INIT INFO
# Provides:          kirim_ke_wayang
# Required-Start:    $remote_fs $syslog
# Required-Stop:     $remote_fs $syslog
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Send data to factory
# Description:       A script to transmit the file to the factory's server.
### END INIT INFO

# ... The rest of your script follows here ...
WATCH_DIR="/home/wayang/untuk_wayang" # Replace with the directory to monitor
RCLONE_REMOTE="wyg:wayang$" # Replace with your rclone remote and destination
HTTP_SERVER_URL="http://10.10.3.10/GF_GDriv/get_file.php"
inotifywait -r -m -e close_write -e moved_to "$WATCH_DIR" |
while read -r directory action file; do
  FULL_PATH="$directory/$file"
  if [[ -f "$FULL_PATH" ]]; then # Ensure it's a regular file
    if [[ "$file" =~ \.zip$ ]]; then
	
        FOLDER="${directory#$WATCH_DIR}"

      echo "Detected ZIP file: $file. Sending via rclone..."
      rclone copy "$FULL_PATH" "$RCLONE_REMOTE$FOLDER"
      RCLONE_EXIT_CODE=$?
      if [ $RCLONE_EXIT_CODE -eq 0 ]; then
        echo "File sent successfully via rclone."
        # Make HTTP request (example using curl)
        curl -X POST -d "file=$file&&folder=$FOLDER" "$HTTP_SERVER_URL"
        #curl -X POST -H "Content-Type: application/json" -d '{"status": "success", "file": "'"$filename"'"}' "$HTTP_SERVER_URL"
        echo "HTTP request sent to $HTTP_SERVER_URL"
      else
        echo "Rclone transfer failed for $filename. Exit code: $RCLONE_EXIT_CODE"
      fi
     else
      echo "Detected non-ZIP file: $file. Zipping file"
      ZIP_FILE="${FULL_PATH}.zip"
      zip -Tmj  "$ZIP_FILE" "$FULL_PATH" # -j option removes directory structure

    fi

   elif [ -d "$FULL_PATH" ]; then
	 rclone mkdir "$RCLONE_REMOTE/$file"
	
        #find "$FULL_PATH" -type f -print0 | while IFS= read -r -d $'\0' sub_file; do
            #SUB_FILE_SIZE_KB=$(du -k "$sub_file" | cut -f1)
            #if (( SUB_FILE_SIZE_KB > SIZE_THRESHOLD_KB )); then
                #echo "File $sub_file in directory $FULL_PATH is too large ($SUB_FILE_SIZE_KB KB). Zipping..."
                #zip -j "${sub_file}.zip" "$sub_file"
                #rm "$sub_file" # Optional: remove original file after zipping
            #fi
        #done
    fi

done
