#!/bin/bash

# (c) cavaliba.com - importer.sh

# SETUP:  choose run mode (auto cron / manual)
#  --------------------------------------------
# cron mode (no TTY in docker command)
# 32 15 * * * /opt/cavaliba/script/importer.sh /opt/cavaliba > /var/log/cavaliba_importer.log 2>&1
#CAVALIBA="docker exec -i cavaliba_app python manage.py cavaliba "

# manual mode (TTY in docker command) ; from cavaliba home dir
CAVALIBA="docker exec -it cavaliba_app python manage.py cavaliba "

#TIMESTAMP=$(date +"%Y-%m-%d-%H-%M-%S")
TIMESTAMP=$(date +"%Y-%m-%d")

# relative to HOMEDIR
HOMEDIR="${1:-.}"
IMPORT_FOLDER="files/import/"
OLD_FOLDER="files/import/_old"
KEEPDAYS=7

# Function to log messages with timestamp
log() {
	local level="$1"
	local message="$2"
	local current_time=$(date +"%Y-%m-%d %H:%M:%S")
	local log_output="[$current_time] [$level] $message"
	echo "$log_output"
}


# Function to move old files to _old folder
cleanup_old_files() {

	if [ ! -d "$OLD_FOLDER" ]; then
		log "INFO" "Creating _old folder: $OLD_FOLDER"
		mkdir -p "$OLD_FOLDER"
	fi

	
	log "INFO" "Cleaning files older than $KEEPDAYS days from $OLD_FOLDER"

	find "$OLD_FOLDER" -maxdepth 1 -type f -mtime +$KEEPDAYS | while read -r file; do
		filename=$(basename "$file")
		# Ignore files starting with a dot
		if [[ "$filename" == .* ]]; then
			continue
		fi
		log "INFO" "Removing old file: $filename"
		rm -f "$file"
	done
}

# Function to import files
import_files() {
	

    filename="user.csv"
    fullname="$IMPORT_FOLDER/$filename"


    if [ ! -f "$fullname" ]; then
        log "Error: file not found:  $fullname"
        exit 1
    fi

	log "INFO" "Import file: $fullname"
    $CAVALIBA load "$fullname" --pipeline user_csv
    
    log "INFO" "Move file: $fullname" 
	mv "$fullname" $OLD_FOLDER/"$filename"-$TIMESTAMP

    # Here, add more imports
    # ...
}

#  ----------------------------------------------------------------
# entry point
#  ----------------------------------------------------------------

# Change to HOMEDIR
cd "$HOMEDIR" || exit 1

# Check for required files and directories
if [ ! -f "$HOMEDIR/.env" ]; then
	echo "Error: .env file not found in $HOMEDIR"
	exit 1
fi

if [ ! -f "$HOMEDIR/docker-compose.yml" ]; then
	echo "Error: docker-compose.yml file not found in $HOMEDIR"
	exit 1
fi

if [ ! -d "$HOMEDIR/files" ]; then
	echo "Error: files/ folder not found in $HOMEDIR"
	exit 1
fi

# Purge logfile at startup if it exists
# if [ -f "$LOGFILE" ]; then
# 	rm -f $LOGFILE
# fi

# Log script startup
log "INFO" "Import startup at $(date +"%Y-%m-%d %H:%M:%S")"

# Imports
import_files

# Cleanup old files
cleanup_old_files

# Log script completion
log "INFO" "Script done at $(date +"%Y-%m-%d %H:%M:%S")"
