#!/bin/bash
clear
echo " ______    _______  ______   __   __  ___  __    _  _______                   ";
echo "|    _ |  |       ||      | |  |_|  ||   ||  |  | ||       |                  ";
echo "|   | ||  |    ___||  _    ||       ||   ||   |_| ||    ___|                  ";
echo "|   |_||_ |   |___ | | |   ||       ||   ||       ||   |___                   ";
echo "|    __  ||    ___|| |_|   ||       ||   ||  _    ||    ___|                  ";
echo "|   |  | ||   |___ |       || ||_|| ||   || | |   ||   |___                   ";
echo "|___|  |_||_______||______| |_|   |_||___||_|  |__||_______|                  ";
echo " ___  __    _  _______  _______  _______  ___      ___      _______  ______   ";
echo "|   ||  |  | ||       ||       ||   _   ||   |    |   |    |       ||    _ |  ";
echo "|   ||   |_| ||  _____||_     _||  |_|  ||   |    |   |    |    ___||   | ||  ";
echo "|   ||       || |_____   |   |  |       ||   |    |   |    |   |___ |   |_||_ ";
echo "|   ||  _    ||_____  |  |   |  |       ||   |___ |   |___ |    ___||    __  |";
echo "|   || | |   | _____| |  |   |  |   _   ||       ||       ||   |___ |   |  | |";
echo "|___||_|  |__||_______|  |___|  |__| |__||_______||_______||_______||___|  |_|";
echo " 																				";
echo " R E D M I N E  /  m a r i a D B 1 1   i n s t a l l e r                      ";
echo " f o r   D e b i a n   1 2   B o o k w o r m 									";
echo " 																				";
echo " 																				";

# Function to prompt user input with default values
function prompt_with_default() {
  local prompt_text=$1
  local default_value=$2
  local input

  # Custom prompt with 'Default=' format
  read -p "$prompt_text`echo $'\nDEFAULT='`[$default_value]> " input
  # Use default value if no input is provided
  echo ${input:-$default_value}
}

# Function to ask for and confirm variables
function get_user_inputs() {
  # Interactive prompts with default values
  DB_NAME=$(prompt_with_default "# 1. You can choose a database name." "redmine")
  DB_USER=$(prompt_with_default "# 2. Now you can choose a database user." "redmine")
  DB_PASSWORD=$(prompt_with_default "# 3. Please choose a database password." "DBPassword123")
  ADMIN_PASSWORD=$(prompt_with_default "# 4. Please choose a Redmine initial admin password." "Password123")
  REDMINE_VERSION=$(prompt_with_default "# 5. Please enter the Redmine version to install." "5.1.2")
  REDMINE_DIR=$(prompt_with_default "# 6. Please choose a Redmine installation directory." "/var/www/redmine")
  REDMINE_URL=$(prompt_with_default "# 7. Here you can modify the Source for the installation." "https://www.redmine.org/releases/redmine-$REDMINE_VERSION.tar.gz")
  LOG_FILE=$(prompt_with_default "# 8. Please choose a path for the Logfile." "/var/log/redmine_installation.log")
}

# Function to confirm inputs
function confirm_inputs() {
  echo "--------------------------------------------"
  echo "Please review the following settings:"
  echo "Database name:           $DB_NAME"
  echo "Database user:           $DB_USER"
  echo "Database password:       $DB_PASSWORD"
  echo "Admin password:          $ADMIN_PASSWORD"
  echo "Redmine version:         $REDMINE_VERSION"
  echo "Redmine directory:       $REDMINE_DIR"
  echo "Redmine URL:             $REDMINE_URL"
  echo "--------------------------------------------"
  
  read -p "Are these settings correct? Then we continue with the setup of Apache, MySQL/mariaDB, phpmyadmin and Redmine.  (y/n): " confirm
  if [[ "$confirm" != "y" ]]; then
    echo "Please enter the data again..."
    return 1
  fi
  return 0
}

# Main loop to confirm or re-enter inputs
while true; do
  get_user_inputs
  confirm_inputs && break
done

# Remaining script...
log "Updating system..."
apt update && apt upgrade -y && apt install sudo -y

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

# Update system
log "Updating system..."
apt update 2>&1 | tee -a $LOG_FILE
apt upgrade -y 2>&1 | tee -a $LOG_FILE
apt install sudo -y 2>&1 | tee -a $LOG_FILE

# Install dependencies
log "Installing necessary packages..."
apt install -y apache2 libapache2-mod-passenger mariadb-server mariadb-client \
  libmariadb-dev build-essential libssl-dev libyaml-dev libxml2-dev \
  libxslt1-dev libffi-dev zlib1g-dev libmagickwand-dev curl vim git wget php libapache2-mod-php php-mysql 2>&1 | tee -a $LOG_FILE

# Add MariaDB repository
log "Adding the MariaDB repository..."
apt-get install -y apt-transport-https curl 2>&1 | tee -a $LOG_FILE
mkdir -p /etc/apt/keyrings
curl -o /etc/apt/keyrings/mariadb-keyring.pgp 'https://mariadb.org/mariadb_release_signing_key.pgp' 2>&1 | tee -a $LOG_FILE
echo "deb [signed-by=/etc/apt/keyrings/mariadb-keyring.pgp] https://ftp.agdsn.de/pub/mirrors/mariadb/repo/11.4/debian bookworm main" | tee /etc/apt/sources.list.d/mariadb.list
apt-get update 2>&1 | tee -a $LOG_FILE

# Update MariaDB to version 11.4
log "Updating MariaDB to version 11.4..."
apt-get install -y mariadb-server 2>&1 | tee -a $LOG_FILE

# Start and secure MariaDB
log "Configuring MariaDB..."
systemctl start mariadb 2>&1 | tee -a $LOG_FILE
systemctl enable mariadb 2>&1 | tee -a $LOG_FILE
mysql_secure_installation <<EOF 2>&1 | tee -a $LOG_FILE

y
$DB_PASSWORD
$DB_PASSWORD
y
y
y
y
EOF

# Create database and user for Redmine
log "Creating database and user for Redmine..."
mysql -u root -p$DB_PASSWORD <<MYSQL_SCRIPT 2>&1 | tee -a $LOG_FILE
CREATE DATABASE $DB_NAME CHARACTER SET utf8mb4;
CREATE USER '$DB_USER'@'localhost' IDENTIFIED BY '$DB_PASSWORD';
GRANT ALL PRIVILEGES ON $DB_NAME.* TO '$DB_USER'@'localhost';
FLUSH PRIVILEGES;
EXIT;
MYSQL_SCRIPT

# Install phpMyAdmin
log "Installing phpMyAdmin..."
# Silently install phpMyAdmin
log "Silently installing phpMyAdmin with apache2 and dbconfig-common..."

# Set preconfiguration for phpMyAdmin
echo "phpmyadmin phpmyadmin/reconfigure-webserver multiselect apache2" | debconf-set-selections
echo "phpmyadmin phpmyadmin/dbconfig-install boolean true" | debconf-set-selections
echo "phpmyadmin phpmyadmin/app-password-confirm password $DB_PASSWORD" | debconf-set-selections
echo "phpmyadmin phpmyadmin/mysql/admin-pass password $DB_PASSWORD" | debconf-set-selections
echo "phpmyadmin phpmyadmin/mysql/app-pass password $DB_PASSWORD" | debconf-set-selections
echo "phpmyadmin phpmyadmin/password-confirm password $DB_PASSWORD" | debconf-set-selections

# Silently install phpMyAdmin
DEBIAN_FRONTEND=noninteractive apt install -y phpmyadmin 2>&1 | tee -a $LOG_FILE

# phpMyAdmin configuration
log "Configuring VirtualHost for phpMyAdmin..."
cat <<EOL > /etc/apache2/sites-available/phpmyadmin.conf
<VirtualHost *:12300>

        ServerName localhost

        <Directory /usr/share/phpmyadmin>
                AllowOverride None
                Require all granted
        </Directory>

        DocumentRoot /usr/share/phpmyadmin

        Include /etc/phpmyadmin/apache.conf

        ErrorLog ${APACHE_LOG_DIR}/phpmyadmin.error.log
        CustomLog ${APACHE_LOG_DIR}/phpmyadmin.access.log combined

</VirtualHost>
EOL

# Enable port 12300
log "Enabling port 12300 for Apache..."
echo "Listen 12300" | tee -a /etc/apache2/ports.conf

a2disconf phpmyadmin 2>&1 | tee -a $LOG_FILE
a2ensite phpmyadmin 2>&1 | tee -a $LOG_FILE
systemctl reload apache2 2>&1 | tee -a $LOG_FILE

# Install Ruby
log "Installing Ruby and Bundler..."
apt install -y ruby-full 2>&1 | tee -a $LOG_FILE
gem install bundler 2>&1 | tee -a $LOG_FILE

# Download and configure Redmine
log "Downloading Redmine $REDMINE_VERSION..."
cd /var/www
wget $REDMINE_URL 2>&1 | tee -a $LOG_FILE
tar -xvzf redmine-$REDMINE_VERSION.tar.gz 2>&1 | tee -a $LOG_FILE
mv redmine-$REDMINE_VERSION redmine
chown -R www-data:www-data $REDMINE_DIR
chmod -R 755 $REDMINE_DIR

# Add Blankslate gem
log "Adding the Blankslate gem to the Gemfile..."
echo "gem 'blankslate', '~> 3.1.3'" | tee -a $REDMINE_DIR/Gemfile

# Configure Redmine database
log "Configuring Redmine database connection..."
cp $REDMINE_DIR/config/database.yml.example $REDMINE_DIR/config/database.yml
# First, remove the existing 'production' block
sed -i '/production:/,/^$/d' $REDMINE_DIR/config/database.yml

# Add new 'production' block
cat <<EOL >> $REDMINE_DIR/config/database.yml
production:
  adapter: mysql2
  database: $DB_NAME
  host: localhost
  username: $DB_USER
  password: "$DB_PASSWORD"
  encoding: utf8mb4
  variables:
    transaction_isolation: "READ-COMMITTED"
EOL

# Install Redmine gems
log "Installing necessary gems..."
cd $REDMINE_DIR
bundle install --without development test 2>&1 | tee -a $LOG_FILE

# Migrate Redmine database
log "Initializing Redmine database..."
bundle exec rake generate_secret_token 2>&1 | tee -a $LOG_FILE
RAILS_ENV=production bundle exec rake db:migrate 2>&1 | tee -a $LOG_FILE
RAILS_ENV=production bundle exec rake redmine:load_default_data <<EOF 2>&1 | tee -a $LOG_FILE
en
EOF

# Create directories and set permissions
log "Setting directory permissions..."
mkdir -p tmp tmp/pdf public/plugin_assets
chown -R www-data:www-data files log tmp public/plugin_assets
chmod -R 755 files log tmp public/plugin_assets

# Apache configuration for Redmine
log "Configuring Apache for Redmine..."
bash -c "cat > /etc/apache2/sites-available/redmine.conf" <<EOF
<VirtualHost *:80>
    ServerAdmin admin@yourdomain.com
    DocumentRoot $REDMINE_DIR/public
    ServerName localhost
    <Directory $REDMINE_DIR/public>
        Require all granted
        Options -MultiViews
    </Directory>
    ErrorLog \${APACHE_LOG_DIR}/redmine_error.log
    CustomLog \${APACHE_LOG_DIR}/redmine_access.log combined
</VirtualHost>
EOF

a2dissite 000-default.conf 2>&1 | tee -a $LOG_FILE
a2ensite redmine.conf 2>&1 | tee -a $LOG_FILE

systemctl reload apache2 2>&1 | tee -a $LOG_FILE

# Change Redmine admin user password
log "Changing the admin password..."
RAILS_ENV=production bundle exec rails runner "user = User.find_by_login('admin'); user.password = '$ADMIN_PASSWORD'; user.password_confirmation = '$ADMIN_PASSWORD'; user.save!" 2>&1 | tee -a $LOG_FILE

log "Installation completed!" 
log "Access Redmine at http://<your_server_ip>."
log "Username: admin"
log "Password: $ADMIN_PASSWORD"
echo " "
log "Access phpmyadmin at http://<your_server_ip>:12300."
log "Username: $DB_USER"
log "Password: $DB_PASSWORD"
echo " "
log "Installation made by allmycookies(c)2024"
