#!/usr/bin/env bash

# Copyright (c) 2021-2026 community-scripts ORG
# Author: MickLesk (CanbiZ)
# License: MIT | https://github.com/community-scripts/ProxmoxVE/raw/main/LICENSE
# Source: https://tomcat.apache.org/

source /dev/stdin <<<"$FUNCTIONS_FILE_PATH"
color
verb_ip6
catch_errors
setting_up_container
network_check
update_os

read -r -p "${TAB3}Which Tomcat version would you like to install? (9, 10.1, 11): " version
case $version in
9)
  TOMCAT_VERSION="9"
  echo "Which LTS Java version would you like to use? (8, 11, 17, 21): "
  read -r jdk_version
  case $jdk_version in
  8 | 11 | 17 | 21)
    JAVA_VERSION="$jdk_version" setup_java
    ;;
  *)
    msg_error "Invalid JDK version selected. Please enter 8, 11, 17 or 21."
    exit 64
    ;;
  esac
  ;;
10 | 10.1)
  TOMCAT_VERSION="10"
  echo "Which LTS Java version would you like to use? (11, 17, 21): "
  read -r jdk_version
  case $jdk_version in
  11 | 17 | 21)
    JAVA_VERSION="$jdk_version" setup_java
    ;;
  *)
    msg_error "Invalid JDK version selected. Please enter 11, 17 or 21."
    exit 64
    ;;
  esac
  ;;
11)
  TOMCAT_VERSION="11"
  echo "Which LTS Java version would you like to use? (17, 21): "
  read -r jdk_version
  case $jdk_version in
  17 | 21)
    JAVA_VERSION="$jdk_version" setup_java
    ;;
  *)
    msg_error "Invalid JDK version selected. Please enter 17 or 21."
    exit 64
    ;;
  esac
  ;;
*)
  msg_error "Invalid Tomcat version selected. Please enter 9, 10.1 or 11."
  exit 64
  ;;
esac

msg_info "Installing Tomcat $TOMCAT_VERSION"
LATEST_VERSION=$(curl -fsSL "https://dlcdn.apache.org/tomcat/tomcat-$TOMCAT_VERSION/" | grep -oP 'v[0-9]+\.[0-9]+\.[0-9]+(-M[0-9]+)?/' | sort -V | tail -n 1 | sed 's/\/$//; s/v//')
TOMCAT_URL="https://dlcdn.apache.org/tomcat/tomcat-$TOMCAT_VERSION/v$LATEST_VERSION/bin/apache-tomcat-$LATEST_VERSION.tar.gz"
curl_download "/tmp/tomcat.tar.gz" "$TOMCAT_URL"
mkdir -p /opt/tomcat-$TOMCAT_VERSION
tar --strip-components=1 -xzf /tmp/tomcat.tar.gz -C /opt/tomcat-$TOMCAT_VERSION
chown -R root:root /opt/tomcat-$TOMCAT_VERSION
rm -f /tmp/tomcat.tar.gz
cat <<EOF >/etc/systemd/system/tomcat.service
[Unit]
Description=Apache Tomcat Web Application Container
After=network.target

[Service]
Type=forking
User=$(whoami)
Group=$(whoami)
Environment=JAVA_HOME=/usr/lib/jvm/temurin-${jdk_version}-jdk-amd64
Environment=CATALINA_HOME=/opt/tomcat-$TOMCAT_VERSION
Environment=CATALINA_BASE=/opt/tomcat-$TOMCAT_VERSION
Environment=CATALINA_PID=/opt/tomcat-$TOMCAT_VERSION/temp/tomcat.pid
ExecStart=/opt/tomcat-$TOMCAT_VERSION/bin/catalina.sh start
ExecStop=/opt/tomcat-$TOMCAT_VERSION/bin/catalina.sh stop
PIDFile=/opt/tomcat-$TOMCAT_VERSION/temp/tomcat.pid
SuccessExitStatus=143
Restart=on-abnormal

[Install]
WantedBy=multi-user.target
EOF
systemctl enable -q --now tomcat
msg_ok "Tomcat $LATEST_VERSION installed and started"

motd_ssh
customize
cleanup_lxc
