#!/bin/bash
SCRIPT_VERSION="1.0.0"

## ========================= INSTALL ARRS ===================================

set -euo pipefail

if [ ! -f /root/.post_update ]; then
  echo "Running updates..."

  apt update && apt upgrade -y
  apt autoremove -y
  apt install curl -y
  timedatectl set-timezone America/Los_Angeles
  echo "America/Los_Angeles" > /etc/timezone

  touch /root/.post_update

  # Yellow text output
  echo -e "\033[1;33mAfter reboot re-run the script to complete...\033[0m"
  sleep 4

  reboot
  exit 0
fi

#====================  Varibales ============================

# ================== Install Binutils =======================
sudo apt install binutils

# Defaults
USERNAME="portain"
GROUPNAME="lxc_shares"
GROUPID=10000

echo "Checking if user '$USERNAME' exists..."

if id "$USERNAME" &>/dev/null; then
    echo "User '$USERNAME' already exists. Skipping user creation."
else
    echo "Creating user '$USERNAME' (will prompt for password and info)..."
    adduser "$USERNAME"
fi

echo "Adding user '$USERNAME' to sudo group..."
usermod -aG sudo "$USERNAME"

echo "Checking if group '$GROUPNAME' exists..."
if getent group "$GROUPNAME" >/dev/null; then
    echo "Group '$GROUPNAME' already exists. Skipping group creation."
else
    groupadd -g "$GROUPID" "$GROUPNAME"
    echo "Group '$GROUPNAME' created with GID $GROUPID."
fi

echo "Adding user '$USERNAME' to group '$GROUPNAME'..."
usermod -aG "$GROUPNAME" "$USERNAME"

echo "Done."

# Install dependencies for Docker installation
echo "Installing dependencies for Docker..."
sudo apt install -y \
    apt-transport-https \
    ca-certificates \
    curl \
    software-properties-common \
    lsb-release \
    gnupg2 \
    jq

# Add Docker’s official GPG key
sudo rm -f /usr/share/keyrings/docker-archive-keyring.gpg
curl -fsSL https://download.docker.com/linux/ubuntu/gpg | \
sudo gpg --dearmor -o /usr/share/keyrings/docker-archive-keyring.gpg

# Set up the Docker stable repository
echo "Setting up Docker repository..."
echo "deb [arch=amd64 signed-by=/usr/share/keyrings/docker-archive-keyring.gpg] https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable" | sudo tee /etc/apt/sources.list.d/docker.list > /dev/null

# Update package index again after adding Docker repo
echo "Updating package index..."
sudo apt update -y

# Install Docker CE
echo "Installing Docker CE..."
sudo apt install -y docker-ce docker-ce-cli containerd.io

# Start and enable Docker service
echo "Starting Docker service..."
sudo systemctl start docker
sudo systemctl enable docker

# Install the latest Docker Compose
echo "Installing Docker Compose..."
LATEST_COMPOSE=$(curl -s https://api.github.com/repos/docker/compose/releases/latest | jq -r .tag_name)
sudo curl -L "https://github.com/docker/compose/releases/download/${LATEST_COMPOSE}/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose
sudo chmod +x /usr/local/bin/docker-compose

# Verify Docker and Docker Compose installations
echo "Verifying installations..."
docker --version
docker-compose --version

# Create Docker Compose update script in /opt/scripts/
echo "Creating Docker Compose update script in /opt/scripts/update_compose.sh..."
#sudo mkdir -p /opt/scripts

cat <<EOF | sudo tee /usr/local/bin/update_compose.sh > /dev/null
#!/bin/bash

# Update Docker Compose to the latest version
echo "Updating Docker Compose..."

# Fetch the latest release version from GitHub API
LATEST_COMPOSE=$(curl -s https://api.github.com/repos/docker/compose/releases/latest | jq -r .tag_name)

# Download and install the latest Docker Compose
sudo curl -L "https://github.com/docker/compose/releases/download/${LATEST_COMPOSE}/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose

# Make it executable
sudo chmod +x /usr/local/bin/docker-compose

# Verify the installation
docker-compose --version

echo "Docker Compose updated to the latest version."
EOF

# Make the update script executable
sudo chmod +x /usr/local/bin/update_compose.sh

# Create systemd service and timer for running this script every Monday at 2AM
sudo bash -c 'cat <<EOF > /etc/systemd/system/update-compose.service
[Unit]
Description=Update Docker Compose to latest version
Wants=network-online.target
After=network-online.target

[Service]
Type=oneshot
ExecStart=/usr/local/bin/update-compose.sh
EOF'

sudo bash -c 'cat <<EOF > /etc/systemd/system/update-compose.timer
[Unit]
Description=Run Docker Compose updater every Monday at 2AM

[Timer]
OnCalendar=Mon *-*-* 02:00:00
Persistent=true

[Install]
WantedBy=timers.target
EOF'

# Step 4: Reload systemd and enable/start the timer
sudo systemctl daemon-reexec
sudo systemctl daemon-reload
sudo systemctl enable --now update-compose.timer

# ========= Script Update Checker =========
sudo tee /usr/local/bin/script_updater.sh > /dev/null <<'EOF'
#!/bin/bash

# ========= Script Update Checker Notes =========
# This script checks the version of a local script against a remote version
# hosted on Nextcloud. If a newer version is found, it downloads and replaces
# the local script, backing up the old one.
#
# Logs updates and errors to /var/log/script-update.log.
# Creates a flag file /var/log/script-updated.flag on successful update.
#
# Designed to be run periodically (e.g., via systemd timer).
# ========================================

LOCAL_SCRIPT="/root/paperless-ngx.sh"   # Change to your actual script path
NEXTCLOUD_URL="https://nextcloud.home.rschedules.io/s/H84d2sZMANBwqnm/download"  # Replace with your actual public Nextcloud link

LOGFILE="/var/log/script-update.log"
FLAGFILE="/var/log/script-updated.flag"

curl_opts=(--fail --silent --show-error --location --max-time 20)

log() {
  echo "[$(date '+%F %T')] $*" >> "$LOGFILE"
}

get_version_from_content() {
  # Use strings to avoid binary grep issues
  strings "$1" | grep '^SCRIPT_VERSION=' | head -n1 | cut -d'"' -f2 || echo ""
}

get_remote_version() {
  tmpf=$(mktemp)
  if curl "${curl_opts[@]}" --output "$tmpf" "$NEXTCLOUD_URL"; then
    log "Successfully downloaded remote file to $tmpf"

    {
      echo "------ START OF REMOTE FILE HEAD ------"
      head -n 20 "$tmpf"
      echo "------ END OF REMOTE FILE HEAD --------"
    } >> "$LOGFILE"

    v=$(get_version_from_content "$tmpf")
    rm -f "$tmpf"
    echo "$v"
  else
    log "Curl failed to download remote script from $NEXTCLOUD_URL"
    rm -f "$tmpf"
    echo ""
  fi
}

get_local_version() {
  if [[ -f "$LOCAL_SCRIPT" ]]; then
    get_version_from_content "$LOCAL_SCRIPT"
  else
    echo ""
  fi
}

version_greater() {
  ver_to_num() {
    printf '%03d%03d%03d\n' $(echo "$1" | tr '.' ' ')
  }
  [[ "$(ver_to_num "$1")" > "$(ver_to_num "$2")" ]]
}

download_and_replace() {
  tmpf=$(mktemp)
  BACKUP_DIR="/root/script-backups"
  mkdir -p "$BACKUP_DIR"

  if curl "${curl_opts[@]}" --output "$tmpf" "$NEXTCLOUD_URL"; then
    chmod +x "$tmpf"
    if [[ -f "$LOCAL_SCRIPT" ]]; then
      # Backup filename with month-day-year format
      backup="${BACKUP_DIR}/$(basename "$LOCAL_SCRIPT").bak.$(date +%m-%d-%Y_%H-%M-%S)"
      cp "$LOCAL_SCRIPT" "$backup"
      log "Backed up old script to $backup"

      # Cleanup backups older than 7 days
      find "$BACKUP_DIR" -name "$(basename "$LOCAL_SCRIPT").bak.*" -type f -mtime +7 -exec rm -f {} \;
      log "Deleted backup files older than 7 days from $BACKUP_DIR"
    fi
    mv "$tmpf" "$LOCAL_SCRIPT"
    log "Updated script to new version"
    touch "$FLAGFILE"
  else
    log "Failed to download updated script"
    rm -f "$tmpf"
  fi
}

check_for_update() {
  local local_ver remote_ver
  local_ver=$(get_local_version)
  remote_ver=$(get_remote_version)

  if [[ -z "$remote_ver" ]]; then
    log "Failed to fetch remote version — cannot proceed."
    echo "Failed to fetch remote version."
    return 1
  fi

  if [[ -z "$local_ver" ]]; then
    log "Local version missing or unreadable, installing remote version $remote_ver"
    download_and_replace
    echo "Installed new script version $remote_ver."
    return 0
  fi

  if version_greater "$remote_ver" "$local_ver"; then
    echo "Update available: remote version $remote_ver"
    log "Update available: remote version $remote_ver > local version $local_ver"
    download_and_replace
  else
    echo "No update needed: local version $local_ver is up to date."
    log "No update needed: remote version $remote_ver <= local version $local_ver"
  fi
}

# Run the check
check_for_update
EOF

# Make the script executable
sudo chmod +x /usr/local/bin/script_updater.sh

echo "Script installed at /usr/local/bin/update-script.sh and made executable."

# Create the systemd service unit
sudo tee /etc/systemd/system/script-updater.service > /dev/null <<EOF
[Unit]
Description=Run script update check

[Service]
Type=oneshot
ExecStart=/usr/local/bin/update-script.sh
EOF

# Create the systemd timer unit
sudo tee /etc/systemd/system/script-updater.timer > /dev/null <<EOF
[Unit]
Description=Run update-script weekly on Mondays at 2 AM

[Timer]
OnCalendar=Mon 02:00:00
Persistent=true

[Install]
WantedBy=timers.target
EOF

# Reload systemd and enable the timer
sudo systemctl daemon-reload
sudo systemctl enable --now script-updater.timer
# ========= End Script Update Checker =========

## Install Portainer CE
docker volume create portainer_data
docker run -d -p 8000:8000 -p 9443:9443 --name portainer --restart=always -v /var/run/docker.sock:/var/run/docker.sock -v portainer_data:/data portainer/portainer-ce:lts

sudo tee /usr/local/bin/update.sh > /dev/null << 'EOF'
#!/bin/bash

## Update Portainer CE
docker stop portainer
docker rm portainer
docker pull portainer/portainer-ce:lts
docker run -d -p 8000:8000 -p 9443:9443 --name=portainer --restart=always -v /var/run/docker.sock:/var/run/docker.sock -v portainer_data:/data portainer/portainer-ce:lts

echo "Portainer is updated to the latest version."
EOF

sudo chmod +x /usr/local/bin/update.sh

# Ask to delete the script
echo -ne "\nDo you want to delete this install script? (y/n) [auto-cancel in 10s]: "
read -t 10 -n 1 delete_answer
delete_answer=${delete_answer:-n}  # default to no
echo

# Ask to reboot
echo -ne "\nDo you want to reboot? (y/n) [auto-cancel in 10s]: "
read -t 10 -n 1 reboot_answer
reboot_answer=${reboot_answer:-n}  # default to no
echo

# Handle deletion first (before reboot)
if [[ "$delete_answer" =~ ^[Yy]$ ]]; then
    script_path="$(realpath "${BASH_SOURCE[0]}")"
    echo "Deleting install script: $script_path"
    rm -f "$script_path"
    echo "Install script deleted."
else
    echo "Install script not deleted."
fi

# Handle reboot
if [[ "$reboot_answer" =~ ^[Yy]$ ]]; then
    echo "Rebooting now..."
    sleep 2
    reboot
elif [[ "$reboot_answer" =~ ^[Nn]$ ]]; then
    echo "Reboot canceled by user."
else
    echo "No input received. Reboot canceled."
fi
