#!/bin/bash

# Set parameters
new_version="1.1.2_rc2"
file="/etc/pam.d/common-session"
script_path="/opt/bin/operation_record.sh"
profile_path="/etc/profile"
log_dir="/var/log/operation"
order_id=$1
OrderFile="/opt/.foggie_order"
HostIp=$(hostname -I | awk '{ for(i=1;i<=NF;i++) { if (! ($i ~ /^192\.168\./ || $i ~ /^10\./ || $i ~ /^172\.(1[6-9]|2[0-9]|3[01])\./ )) print $i } }')
HostName="${HostIp//./-}"
DownUrlPath="http://dl.fogworks.io/facmgr_rc2_1.1.2_test/facmgr.tar.bz2"
InstallPath="/opt"
InstallDir="$InstallPath/facmgr"
InstallPacketPath="$InstallPath/facmgr.tar.bz2"
SERVICE_FILE_URL="/opt/facmgr/app/config/facmgr.service"
SERVICE_FILE_PATH="/etc/systemd/system/facmgr.service"
LOG_DIR="/var/log/facmgr"
DataDIR="/data"
FACMGR_DIR="$DataDIR/facmgr"
FACMGR_DB="$DataDIR/facmgr/sqlite3.db"
FACMGR_LOG="$DataDIR/facmgr/log"
BACKUP_DIR="$DataDIR/facmgr/backup"
LOG_FILE="$LOG_DIR/facmgr_install.log"
DIRS=("$DataDIR" "$LOG_DIR" "$FACMGR_DIR" "$FACMGR_LOG" "$BACKUP_DIR")
limits_conf="/etc/security/limits.conf"
config_lines=(
    "* soft nofile 65535"
    "* hard nofile 65535"
    "root soft nofile 65535"
    "root hard nofile 65535"
)

create_log() {

  if [ ! -f "$LOG_FILE" ]; then
    mkdir -p "$LOG_DIR"
    touch "$LOG_FILE"
  fi

}


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

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


create_directory() {
  local dir="$1"
  if [ ! -d "$dir" ]; then
    log "Directory $dir does not exist. Creating..."
    mkdir -p "$dir" || {
      log "Failed to create directory $dir"
      exit 1
    }
  fi
}


update_dns() {
# Set DNS server
  echo "nameserver 8.8.8.8" > /etc/resolv.conf
  if [ ! -f "/etc/resolv.conf" ]; then
    echo "nameserver 8.8.4.4" > /etc/resolv.conf
  elif ! grep -q "nameserver 8.8.4.4" /etc/resolv.conf; then
    echo "nameserver 8.8.4.4" >> /etc/resolv.conf
  fi

}


add_limit(){

if [ -f "$limits_conf" ]; then
    for line in "${config_lines[@]}"; do
        if grep -q "^$line" "$limits_conf"; then
            echo "The configuration '$line' already exists and does not need to be modified"
        else
            echo "$line" | tee -a "$limits_conf"
        fi
    done
else
    for line in "${config_lines[@]}"; do
        echo "$line" | tee -a "$limits_conf"
    done

fi

if ! grep -q "session required pam_limits.so" "$file"; then
    echo "session required pam_limits.so" >> "$file"
fi

}

add_order(){
  if [ ! -s "${OrderFile}" ]; then
    echo "$order_id" > "${OrderFile}"
  fi
}




facmgr_install() {
  # Remove the old file
  if [ -e $InstallPacketPath ]; then
    rm $InstallPacketPath
    log "Old Packet removed."
  fi

  # Remove the old dir
  if [ -d $InstallDir ]; then
    rm -r $InstallDir
    log "Old Packet dir removed."
  fi

  # Download the new file
  wget $DownUrlPath -P $InstallPath
  log "New file downloaded."

  # Unzip the new file
  tar -xf $InstallPacketPath -C $InstallPath
  log "New file unzipped."
  chmod +x $InstallDir/app/cmd/facmgr
  # Check if the systemctl service exists
  if ! systemctl list-units --full --all | grep -Fq "facmgr.service"; then
    log "facmgr.service does not exist. Downloading..."
    cp $SERVICE_FILE_URL $SERVICE_FILE_PATH
    systemctl daemon-reload
    systemctl enable facmgr.service
  fi
  systemctl restart facmgr.service
  log "All services started successfully."
}




system_service() {
  systemctl stop paloma_agent.service
  systemctl disable paloma_agent.service

  systemctl stop snapd.socket
  systemctl disable snapd.socket
  systemctl stop snapd
  systemctl disable snapd
  # Set hostname
  hostnamectl set-hostname ${HostName}
  # Add entry to hosts file
  sed -i "/^$HostIp/c\\$HostIp ${HostName}" /etc/hosts
  # Check qemu-guest-agent
  if ! systemctl is-active --quiet qemu-guest-agent
  then
    log "Starting qemu-guest-agent..."
    systemctl start qemu-guest-agent
    systemctl enable qemu-guest-agent
    log "qemu-guest-agent has been started and enabled."
  else
    log "qemu-guest-agent is already running."
  fi

}

function check_command {
  if [ $? -eq 0 ]; then
    log "$1 successfully installed."
  else
    log "Failed to install $1. Please check your network connection and try again."
    exit 1
  fi
}


# Function to check if a package is installed
function is_package_installed() {
    if dpkg -s $1 >/dev/null 2>&1; then
        return 0
    else
        return 1
    fi
}

# Function to install a package if it is not already installed
function install_package() {
    MAX_RETRIES=3
    RETRIES=0

    if ! is_package_installed $1; then
        while [ $RETRIES -lt $MAX_RETRIES ]; do
            echo "Installing $1..."
            apt-get install -y $1
            if [ $? -eq 0 ]; then
                echo "$1 successfully installed."
                break
            else
                RETRIES=$((RETRIES + 1))
                echo "Failed to install $1. Retrying... (Attempt $RETRIES)"
            fi
        done

        if [ $RETRIES -eq $MAX_RETRIES ]; then
            echo "Failed to install $1 after $MAX_RETRIES attempts. Please check your network connection and try again."
            exit 1
        fi
    else
        echo "$1 is already installed. Skipping..."
    fi
}

package_install(){
  if [ -f /var/lib/dpkg/lock ]; then
    rm /var/lib/dpkg/lock
  fi
  dpkg --configure -a
  apt update -y

  install_package sqlite3
  install_package docker-ce
  install_package docker-compose
  check_command "sqlite3"
  check_command "docker-ce"
  check_command "docker-compose"


}
cron_job(){
  # Define cron jobs
  BACKUP_JOB_IDENTIFIER="# FACMGR_DB_BACKUP_JOB"
  CRON_JOB_BACKUP="$BACKUP_JOB_IDENTIFIER\n0 1 * * * /usr/bin/env sqlite3 $FACMGR_DB '.backup '$BACKUP_DIR/db_backup_'\$(date +\%Y\%m\%d\%H\%M)'.sqlite'"

  CLEANUP_JOB_IDENTIFIER="# FACMGR_DB_CLEANUP_JOB"
  CRON_JOB_CLEANUP="$CLEANUP_JOB_IDENTIFIER\n0 2 * * * /usr/bin/env find $BACKUP_DIR -name 'db_backup_*.sqlite' -mtime +30 -delete"

  # Add the backup cron job if it does not exist
  if ! crontab -l | grep -q "$BACKUP_JOB_IDENTIFIER"; then
    (crontab -l 2>/dev/null; echo -e "$CRON_JOB_BACKUP") | crontab -
  fi

  # Add the cleanup cron job if it does not exist
  if ! crontab -l | grep -q "$CLEANUP_JOB_IDENTIFIER"; then
    (crontab -l 2>/dev/null; echo -e "$CRON_JOB_CLEANUP") | crontab -
  fi
}


add_oper_log(){
mkdir -p "$(dirname "$script_path")"
mkdir -p "$log_dir"

cat << 'EOF' > "$script_path"

{
  if [ ! -d /var/log/operation ]
  then
      mkdir /var/log/operation
      if [ `id -u` -eq 0 ]
      then
          chattr +a /var/log/operation
      fi
  fi

  file=/var/log/operation/`date '+%y-%m-%d'`.log
  if [ ! -f $file ]
  then
      touch $file
      chmod 777 $file
  fi

  echo $(date "+%y-%m-%d %T ## $(who am i |awk "{print \$1\" \"\$2\" \"\$5}") ## $(pwd) ## $(history 1 | sed 's/^[ \t]*//g' |cut -d " " -f2-)";) >> $file
} 2>/dev/null




EOF

chmod +x "$script_path"

if ! grep -q "PROMPT_COMMAND=$script_path" "$profile_path"; then
  echo "PROMPT_COMMAND=$script_path" >> "$profile_path"
  source "$profile_path"
fi
}

get_current_version() {
    if [ -f "/opt/.version" ]; then
        cat "/opt/.version"
    fi
}

# Function to update the version number and write to the file
update_version() {
    local current_version=$(get_current_version)
    echo "$new_version" > "/opt/.version"

    #if [ -z "$current_version" ]; then
    #    echo "Updating version to $new_version..."
    #    echo "$new_version" > "/opt/.version"
    #else
    #    echo "Version already exists: $current_version. Skipping update."
    #fi
}


cron_upgrade() {

    command_to_run="curl http://dl.fogworks.io/facmgr_test/install.sh | bash"
    logfile="/var/log/facmgr_cron.log"

    existing_cron=$(crontab -l 2>/dev/null)
    if [[ $existing_cron == *"curl http://dl.fogworks.io/facmgr"* ]]; then
        new_cron=$(echo "$existing_cron" | grep -v "curl http://dl.fogworks.io/facmgr")
        echo "$new_cron" | crontab -
        log "Existing cron job(s) with '$command_to_run' removed"
    fi

    (crontab -l 2>/dev/null; echo "0 0 * * * $command_to_run >> $logfile 2>&1") | crontab -
    echo "New cron job added: $command_to_run"
    service cron restart

}

main() {
  check_root
  create_log
  for dir in "${DIRS[@]}"; do
    create_directory "$dir"
  done
  package_install
  update_dns
  add_limit
  add_order
  system_service
  facmgr_install
  add_oper_log
  cron_job 
  update_version
  cron_upgrade
}

main
log "Cron jobs for database backup and cleanup are created."
