#!/bin/bash
set -e

PASS=${1:-timemachine}
QUOTA_SIZE=${2:-0}
NETBIOS=${3:-timemachine}
#SAMBA_PATH=${4:-/data/vfs/bucket_baeqaemjq/samba}
SAMBA_PATH=${4:-/data/time}
SHARENAME=${5:-FoggieXBackup}
USE_CN_MIRROR=${6:-true}

upgrade=false


for arg in "$@"; do
  if [ "$arg" = "-u" ]; then
    upgrade=true
    break
  fi
done


shift $((OPTIND - 1))

# ... Other script code

if [ "$upgrade" = true ]; then
  echo "Upgrade is set to true."
fi



# Define Docker Compose file path and services
COMPOSE_DIR="/opt/smbt_install"
if [ "$USE_CN_MIRROR" = true ]; then
  COMPOSE_FILE="$COMPOSE_DIR/docker-compose-cn.yml"
  SERVICE_FILE_URL="./smbt_docker_cn.service"
else
  COMPOSE_FILE="$COMPOSE_DIR/docker-compose.yml"
  SERVICE_FILE_URL="./smbt_docker.service"
fi

SERVICE_FILE_PATH="/etc/systemd/system/smbt_docker.service"
SERVICES="smbt"

LOG_DIR="/var/log/facmgr"
LOG_FILE="$LOG_DIR/smbt.log"

LAST_UPDATE_FILE="/opt/facmgr/last_smbt_update.txt"


create_log() {
    if [ ! -d "$LOG_DIR" ]; then
        echo "Directory $LOG_DIR does not exist. Creating..."
        mkdir -p "$LOG_DIR"
    fi

    if [ ! -f "$LOG_FILE" ]; then
        touch "$LOG_FILE"
    fi
}

function log {
    echo "$(date +"%Y-%m-%d %H:%M:%S") - $1" | tee -a $LOG_FILE
}

shift $((OPTIND - 1))

if $upgrade; then
  log "Upgrade is set to true."
else
  log "Upgrade is set to false."
fi


check_root() {
    # Check if script is run as root
    if [[ $EUID -ne 0 ]]; then
        log "This script must be run as root"
        exit 1
    fi
}



create_dir() {
    # Create necessary directories if they don't exist
    for DIR in "${DIRS[@]}"; do
        if [ ! -d "$DIR" ]; then
            log "Directory $DIR does not exist. Creating..."
            mkdir -p "$DIR"
        fi
    done
}


delete_image() {
    COMPOSE_FILE="$COMPOSE_FILE"

    # Check if Docker is running
    if ! systemctl is-active --quiet docker; then
        log "Docker is not running. Starting Docker..."
        systemctl start docker
    fi

    if [ "$(docker-compose -f $COMPOSE_FILE ps -q)" ]; then
        log "Docker Compose is running. Restarting..."
        docker-compose -f $COMPOSE_FILE down
    fi

    for service in "${SERVICES[@]}"; do
        if docker ps -aq --filter "name=$service" >/dev/null; then
            docker stop "$service" 2>/dev/null || true
            docker rm "$service" 2>/dev/null || true
            echo "Container $service stopped, removed, and image deleted."
        else
            echo "Container $service does not exist."
        fi
    done


    for image in "${SERVICES[@]}"; do
        if docker images -q "$image" >/dev/null; then
            docker rmi "$image" --force 2>/dev/null || true
            echo "Image $image deleted."
        else
            echo "Image $image does not exist."
        fi
    done
}

pull_image() {
      	
    # Get the last update time
    if [ -f $LAST_UPDATE_FILE ]; then
        LAST_UPDATE=$(cat $LAST_UPDATE_FILE)
    else
        LAST_UPDATE=0
    fi
    export DOCKER_CLIENT_TIMEOUT=600
    export COMPOSE_HTTP_TIMEOUT=600
    log "More than a week has passed since the last update. Checking for updates..."

    COMPOSE_HTTP_TIMEOUT=600 docker-compose -f $COMPOSE_FILE pull
    date +%s > $LAST_UPDATE_FILE

    log "docker-compose pull image"

    if [ $? -eq 124 ]; then
        log "Pull command timed out. Performing individual image pulls..."
        exit 1
    fi
}

function is_port_open {
    if [[ $1 -gt 0 ]]; then
        nc -z localhost "$1" >/dev/null 2>&1
    fi
}

# Check if a service is healthy
function is_service_healthy {
    docker inspect --format "{{json .State.Health.Status }}" $1
    docker inspect --format "{{json .State.Health.Status }}" $1 | grep -q "healthy"
}



env_set() {

    export PASS
    export QUOTA_SIZE
    export NETBIOS

    sed -i '/^export PASS=/d' ~/.bashrc
    echo "export PASS=$PASS" >> ~/.bashrc

    sed -i '/^export QUOTA_SIZE=/d' ~/.bashrc
    echo "export QUOTA_SIZE=$QUOTA_SIZE" >> ~/.bashrc

    sed -i '/^export NETBIOS=/d' ~/.bashrc
    echo "export NETBIOS=$NETBIOS" >> ~/.bashrc

    sed -i '/^export SAMBA_PATH=/d' ~/.bashrc
    echo "export SAMBA_PATH=$SAMBA_PATH" >> ~/.bashrc

    sed -i '/^export SHARENAME=/d' ~/.bashrc
    echo "export SHARENAME=$SHARENAME" >> ~/.bashrc

    if [ -f ~/.bashrc ]; then
        source ~/.bashrc
    fi

    env_file="/opt/smbt_install/.env"
    rm -rf "$env_file"
}




prox_env() {
  env_file="/opt/smbt_install/.env"

  if [ ! -f "$env_file" ]; then
    touch "$env_file"
    echo "Created empty file: $env_file"
  fi
  
  echo "PASS: $PASS"
  echo "QUOTA_SIZE: $QUOTA_SIZE"
  echo "NETBIOS: $NETBIOS"
  echo "USE_CN_MIRROR: $USE_CN_MIRROR"
  echo "SAMBA_PATH: $SAMBA_PATH"

  function write_env_var {
    local var_name=$1
    local var_value=$2

    if [ -f "$env_file" ] && grep -q "^${var_name}=" "$env_file"; then
      echo "Environment variable ${var_name} already exists in $env_file. Skipping writing."
    else
      echo "${var_name}=${var_value}" >> "$env_file"
      echo "Environment variable ${var_name} has been written to $env_file."
    fi
  }

  write_env_var "PASS" "$PASS"
  write_env_var "QUOTA_SIZE" "$QUOTA_SIZE"
  write_env_var "NETBIOS" "$NETBIOS"
  write_env_var "SAMBA_PATH" "$SAMBA_PATH"
  write_env_var "SHARENAME" "$SHARENAME"
}




# Start a service and check its status
function start_service {
    SERVICE_NAME=$1

    log "Starting $SERVICE_NAME..."
    docker-compose -f $COMPOSE_FILE up -d $SERVICE_NAME

    log "$SERVICE_NAME started and is healthy."
}


run_service() {
    # Start services
    for SERVICE in $SERVICES; do
        start_service $SERVICE
    done

    # Check if the systemctl service exists
    if ! systemctl list-units --full --all | grep -Fq "smbt_docker.service"; then
        log "smbt_docker.service does not exist. Downloading..."
        cp -r  $SERVICE_FILE_URL $SERV $SERVICE_FILE_PATH
        systemctl daemon-reload
        systemctl enable smbt_docker.service
    fi

    log "All services started successfully."
}


cron_start_docker(){


(crontab -l 2>/dev/null | grep -v "check_smbt.sh"; echo "* * * * * /etc/cron.d/check_smbt.sh") | crontab -
echo "Cron job updated"




# Create the script file and write the content
script_file="/etc/cron.d/check_smbt.sh"
cat << 'EOF' > "$script_file"
#!/bin/bash

log_file="/var/log/start_smbt_docker.log"

# Check container status and start them
check_and_start_containers() {

        smbt_service_status=$(docker inspect -f '{{.State.Status}}' smbt 2>/dev/null)
        if [ "$smt_service__status" != "running" ]; then
            echo "[$(date +"%Y-%m-%d %H:%M:%S")] smbt container is not running, starting it..." >> "$log_file"
            docker start smbt >> "$log_file" 2>&1
        fi
}

# Check and start container status, and log the actions
check_and_start_containers

echo "[$(date +"%Y-%m-%d %H:%M:%S")] Container check and start script executed" >> "$log_file"
EOF

# Make the script executable
chmod +x "$script_file"
systemctl restart cron.service
log "Cron job has been added, and the script file $script_file has been created."

}

restart_docker() {
    systemctl restart docker
    log "Start to restart Docker"
}


main() {
  create_log
  check_root
  if [ "$upgrade" = false ]; then
      env_set
  fi

  prox_env
  delete_image
  pull_image
  run_service
  cron_start_docker
}
main

log "Cron jobs for smbt are created."
