#!/bin/bash
# This script will help you install dcm4chee-arc-light and related software
# Please read through the script first and customize it

# ============ Customize this part ====================
MYSQLROOTPW=							# MySQL root password
PACSUSER=admin                          # Desired user that will run the server
PACSUSERPASSW=admin                  # users UNIX password
PACSDB=pacsdb                               # MySQL database for dcm4chee-arc-light
DBUSER=pacs                                 # MySQL user 
DBPASS=pacs                                # MySQL password
AET=DCM4CHEE                               # dcm4chee-arc-light AET
ETHINTERFACE=eno1                       # Main ethernet interface for the server
INSTALLDIR=/opt								# Where to create the installation directory
WILDFLYDIR=$INSTALLDIR/dcm4chee				# Installation directory
INSTALLOG=/tmp/dcm4chee-install.log         # Log file for installation
DOWNLOADSDIR=~/Downloads                    # Directory to store downloaded files
# Variables for LDAP install, if not changed will use the server FQDN
#SERVER=$(hostname --fqdn)   # something like: server1.example.com
#DOMAIN=${SERVER#*.}         # something like: example.com
#REALM=$(echo "${DOMAIN}" | tr '[:lower:]' '[:upper:]')   # something like: EXAMPLE.COM
#LDAPROOT=`echo $DOMAIN | sed -e 's/^/dc=/' -e 's/\./\,dc=/'`
LDAPSERVER="$(hostname)"
LDAPDOMAIN="dcm4che.org" 
LDAPREALM="DCM4CHE.ORG" 
LDAPROOT="dc=dcm4che,dc=org"
LDAPADMINPW=admin
MYIP=$IPADDR

# ============ End of Configuration part ==============
# Colors
SR="\e[31m"
SY="\e[33m"
SG="\e[32m"
SD="\e[39m"

APTINSTALL="apt-get --assume-yes -qq install"
WGET="wget -q --show-progress"

# Verify we are runing as root
if [ "$EUID" -ne 0 ]
  then echo -e "\n $SY Please run as root $SD \n"
  exit
fi

# Verify MySQL root password
#if [ -e "/usr/bin/mysql" ]
#then
#    if ! mysql -uroot -p$MYSQLROOTPW -e ";" 2> /dev/null
#    then
#        echo -e "\n $SY Warning! The MySQL root password is not working, please check the config $SD"
#        exit
#    fi
#fi

# Create a directory for downloading files
if [ -e "$DOWNLOADSDIR" ]
then
    echo -e "\n $SY Directory $DOWNLOADSDIR already exists, skipping creation $SD"
else
    mkdir $DOWNLOADSDIR
fi

# Create the dcm4chee user
if getent passwd $PACSUSER > /dev/null 2>&1; then
    echo -e "\n $SY The user $PACSUSER already exists, skipping creation .. $SD"
else
    echo -e "\n $SG Creating user $PACSUSER $SD"
    sudo groupadd $PACSUSER
    sudo useradd -p $(echo $PACSUSERPASSW | openssl passwd -1 -stdin) -d /home/$PACSUSER -m -g $PACSUSER -s /bin/bash $PACSUSER
fi

# Get the IP address of the interface it's going to be used for the server
ETHFOUND=`grep "$ETHINTERFACE" /proc/net/dev`
if [ -n "$ETHFOUND" ]
then
    	if [ -e "/usr/sbin/ifconfig" ]; then
    	echo -e " $SY Ifconfig already installed, skipping... $SD"
	else
    	echo -e " $SG Ifconfig not installed, installing... $SD"
    	$APTINSTALL net-tools > /dev/null
	fi
    IPADDR=`ifconfig $ETHINTERFACE | awk '/inet /{print $2}'`
else
    echo -e "\n $SY Could not find network interface $ETHINTERFACE, please add correct interface in the Configuration part of this script\n $SD"
    exit
fi

# LDAP requires the ROOTDN to match the server FQDN
FQDN=`hostname --fqdn`
if [ "$FQDN" != "$LDAPSERVER" ]
then
    echo -e "\n $SY Warning! Please edit /etc/hosts to reflect the server FQDN name $LDAPSERVER or change the LDAPSERVER config variable $SD"
    echo "      FQDN = $FQDN"
    echo "LDAPSERVER = $FQDN"
    exit
fi


#### Delete old instance of dcm4chee ####

echo -e "\n $SR Warning!! Warning!! This script will now remove all previous install dirs, drop database in MySQL and LDAP"
echo -e " $SR Warning!! Press Enter to continue or Ctrl-C to abort $SD "
read dummy
echo -e "    Warning!! Shutting down running instance"
#$WILDFLYDIR/bin/jboss-cli.sh --connect command=:shutdown >> $INSTALLOG 2>&1
#sleep 5
#for p in `ps -ef | grep wildfly | awk '{print $2}' | tr '\n' ' '`
#do
#    kill -9 $p >> $INSTALLOG 2>&1
#done
systemctl stop dcm4chee
sleep 5
systemctl disable dcm4chee
done

echo -e "    Warning!! Dropping $PACSDB database"
mysqladmin -p$MYSQLROOTPW -f drop $PACSDB >> $INSTALLOG 2>&1


echo -e "    Warning!! Removing install dirs"
rm -rf $WILDFLYDIR >> $INSTALLOG 2>&1

echo -e "    Warning!! Removing LDAP"
/etc/init.d/slapd stop
apt-get --assume-yes -qq purge slapd ldap-utils >> $INSTALLOG 2>&1
rm -rf /var/lib/ldap/ >> $INSTALLOG 2>&1
rm -rf /etc/ldap/schema/* >> $INSTALLOG 2>&1
rm -rf /etc/ldap >> $INSTALLOG 2>&1

#### Install OS software dependencies ####

echo -e "\n $SG Installing OS software dependencies... $SD"
if [ -e "/usr/bin/unzip" ]; then
    echo -e " $SY Zip utilities already installed, skipping... $SD"
else 
    echo -e " $SG Zip utilities not installed, installing... $SD"
    $APTINSTALL zip > /dev/null
fi


if [ -e "/usr/bin/java" ]; then
    JAVAVERSION=`java -version 2>&1 | head -1 | sed -e 's/^.* \"//' -e 's/\./____/2' -e 's/____.*//'`
    if [[ "$JAVAVERSION" > 10.0 ]]
    then
        echo -e " $SY Java already installed, skipping... $SD"
    else
        echo -e " $SR Java is version $JAVAVERSION. Please install java 11, exiting $SD"
        exit 1
    fi
else 
    echo -e " $SG Java not installed, installing... $SD"
    $APTINSTALL --no-install-recommends default-jre > /dev/null
fi 

if [ -e "/usr/bin/lynx" ]; then
    echo -e " $SY Lynx already installed, skipping... $SD"
else
    echo -e " $SG Lynx not installed, installing... $SD"
    $APTINSTALL lynx > /dev/null
fi

if [ -e "/usr/bin/mysql" ]; then
    echo -e " $SY MySQL already installed, skipping... $SD"
else
    echo -e " $SG MySQL not installed, installing... $SD"
    DEBIAN_FRONTEND=noninteractive $APTINSTALL mysql-server > /dev/null
    #$APTINSTALL mysql-server > /dev/null
fi


#echo -e "\n $SG LDAP will be installed with the following parameters $SD"
#echo -e "\nLDAPSERVER:   $SERVER \nLDAPDOMAIN:   $DOMAIN \nLDAPREALM:    $REALM \nLDAPROOT: $LDAPROOT \n"

if [ -e "/usr/sbin/slapd" ]; then
    echo -e " $SY OpenLDAP already installed, skipping... $SD"
else
    echo -e " $SG OpenLDAP not installed, installing... $SD"
    DEBIAN_FRONTEND=noninteractive $APTINSTALL slapd ldap-utils > /dev/null
fi

cd $DOWNLOADSDIR

# Install Wildfly 
if [ -e "wildfly-26.1.2.Final.zip" ]; then
    echo -e "\n $SY Wildfly already downloaded, skipping download... $SD"
else
    echo -e "\n $SG Downloading WildFly 26.1.2... $SD"
    $WGET https://github.com/wildfly/wildfly/releases/download/26.1.2.Final/wildfly-26.1.2.Final.zip
fi
echo -e "  Unpacking Wildfly..."
unzip -q wildfly-26.1.2.Final.zip
mv wildfly-26.1.2.Final $WILDFLYDIR


#### Download dcm4chee-arc-light and related software ####
# Find latest version available of dcm4chee arc light #
echo -ne "\n $SG Looking for latest version of dcm4chee arc light... $SD"
DCMARCVER=`lynx -dump https://sourceforge.net/projects/dcm4che/files/dcm4chee-arc-light5/ | grep files | grep -v timeline | grep "dcm4chee-arc-light5" | sed -e 's/^.*dcm4chee-arc-light5\///' -e 's/\/.*//' | head -1`
#DCMARCVER="5.29.1"
echo -e "(Found dcm4chee-arc-light $DCMARCVER)"
DCMARCURL=`lynx -dump https://sourceforge.net/projects/dcm4che/files/dcm4chee-arc-light5/$DCMARCVER/ | grep mysql.zip | sed -e 's/^.*https/https/'`

# Install dcm4chee-arc-light
if [ -e "dcm4chee-arc-$DCMARCVER-mysql.zip" ]; then
    echo -e " $SY dcm4chee already downloaded, skipping download... $SD"
else
    echo -e " $SG Downloading dcm4chee-arc-light $DCMARCVER ... $SD"
    $WGET $DCMARCURL
    mv download dcm4chee-arc-$DCMARCVER-mysql.zip
fi
	echo -e "  Unpacking dcm4chee dcm4chee-arc-light $DCMARCVER ..."
    unzip -qn dcm4chee-arc-$DCMARCVER-mysql.zip
    cp  -rn dcm4chee-arc-$DCMARCVER-mysql/cli  $WILDFLYDIR/
    cp  -rn dcm4chee-arc-$DCMARCVER-mysql/ldap  $WILDFLYDIR/
    cp  -rn dcm4chee-arc-$DCMARCVER-mysql/sql  $WILDFLYDIR/
    cp  -rn dcm4chee-arc-$DCMARCVER-mysql/configuration  $WILDFLYDIR/standalone
    unzip -qn "dcm4chee-arc-$DCMARCVER-mysql/jboss-modules/*.zip" -d $WILDFLYDIR/
    
# If you wish to install ApacheDirectoryStudio, uncomment below
#if [ -e "ApacheDirectoryStudio-2.0.0.v20210717-M17-linux.gtk.x86_64.tar.gz" ]; then
#    echo -e "\n $SY ADS already downloaded, skipping download... $SD"
#else
#    echo -e "\n $SG Downloading Apache Directory Studio... $SD"
#    $WGET http://ftp.carnet.hr/misc/apache/directory/studio/2.0.0.v20210717-M17/ApacheDirectoryStudio-2.0.0.v20210717-M17-linux.gtk.x86_64.tar.gz
#fi
#    echo -e "Unpacking ADS..."
#    tar -xzf ApacheDirectoryStudio-2.0.0.v20210717-M17-linux.gtk.x86_64.tar.gz
#    mv ApacheDirectoryStudio $INSTALLDIR/


# For secure UI we need overlay and adapter
# Install keycloak-oidc-wildfly-adapter 
if [ -e "keycloak-oidc-wildfly-adapter-20.0.3.zip" ]; then
	echo -e "\n $SY keycloak-oidc-wildfly-adapter-20.0.3 already downloaded, skipping download... $SD"
else
    echo -e "\n $SG Downloading keycloak-oidc-wildfly-adapter-20.0.3.zip ... $SD"
    $WGET https://github.com/keycloak/keycloak/releases/download/20.0.3/keycloak-oidc-wildfly-adapter-20.0.3.zip
fi 
echo -e "  Unpacking keycloak-oidc-wildfly-adapter-20.0.3.zip..."
unzip -qn keycloak-oidc-wildfly-adapter-20.0.3.zip -d $WILDFLYDIR


# If you wish to install dcm4che3 utils, uncomment below
# Find latest version available for dcm4che3 #
#echo -ne "\n $SG Looking for latest version of dcm4che3 download... $SD"
#DCM4CHE3=`lynx -dump https://sourceforge.net/projects/dcm4che/files/dcm4che3/ | grep files | grep -v timeline | grep 5. | sed -e 's/^.*dcm4che3\///' -e 's/\/.*//' | head -1`

#DCM4CHE3="5.29.1"
#echo -e "(Found dcm4che3 $DCM4CHE3)"
#DCM4CHE3URL=`lynx -dump https://sourceforge.net/projects/dcm4che/files/dcm4che3/$DCM4CHE3/ | grep bin.zip | grep download| sed -e 's/^.*https/https/'`

#if [ -e "dcm4che-$DCM4CHE3-bin.zip" ]; then
#    echo -e "\n $SY dcm4che3 tools already  downloaded, skipping download... $SD"
#    echo -e "  Installing dcm4che3 tools"
#    unzip -qn dcm4che-$DCM4CHE3-bin.zip
#    mv dcm4che-2.0.29 $WILDFLYDIR/ ??
#else
#    echo -e "$SG Downloading dcm4che3 tools... $SD"
#    $WGET $DCM4CHE3URL
#    echo -e "  Installing dcm4che3 tools"
#    mv download dcm4che-$DCM4CHE3-bin.zip
#    unzip -qn dcm4che-$DCM4CHE3-bin.zip
#    mv dcm4che-2.0.29 $WILDFLYDIR/ ??
#fi

# Find latest version available for weasis #
echo -ne "\n $SG Looking for latest version of Weasis download... $SD"
WEASISVER=`lynx -dump https://sourceforge.net/projects/dcm4che/files/Weasis/ | grep files | grep -v timeline | grep Weasis | grep -v connector |  grep -v web | sed -e 's/^.*Weasis\///' -e 's/\/.*//' |head -1`
#WEASISVER="3.8.1"
echo -e "(Found Weasis $WEASISVER)"

# Install Weasis
#if [ -e "weasis.war" ]; then
#    echo -e "$SY  Weasis already downloaded, skipping download... $SD"
#    echo -e "$SG  Downloading latest version of weasis.ldif $SD"
#    rm weasis.ldif
#    $WGET "https://dcm4che.atlassian.net/wiki/download/attachments/3670023/weasis.ldif"
#else
#    echo -e "$SG  Downloading Weasis $WEASISVER ... $SD"
#    $WGET https://sourceforge.net/projects/dcm4che/files/Weasis/$WEASISVER/weasis.war/download
#    mv download weasis.war
#    echo -e "$SG Downloading latest version of weasis.ldif $SG"
#    rm weasis.ldif
#    $WGET "https://dcm4che.atlassian.net/wiki/download/attachments/3670023/weasis.ldif"
#fi
#if [ -e "weasis-ext.war" ]; then
#    echo -e "$SY  weasis-ext.war already downloaded, skipping download... $SD"
#else
#    echo -e "$SG  Downloading weasis-ext.war $WEASISVER ... $SD"
#    $WGET https://sourceforge.net/projects/dcm4che/files/Weasis/$WEASISVER/weasis-ext.war/download
#   mv download weasis-ext.war
#fi

#if [ -e "weasis-i18n.war" ]; then
#    echo -e "$SY  Weasis ext already downloaded, skipping download... $SD"
#else
#    echo -e "$SG  Downloading weasis-i18n.war ... $SD"
#    $WGET https://github.com/nroduit/mvn-repo/raw/master/org/weasis/weasis-i18n-dist/3.0.0-SNAPSHOT/weasis-i18n.war/download
#   mv download weasis-i18n.war
#fi
#echo -e "  Installing Weasis $WEASISVER"
#cp -n weasis.ldif $WILDFLYDIR/ldap/
#cp -n weasis.war $WILDFLYDIR/standalone/deployments/ >> $INSTALLOG 2>&1
#cp -n weasis-ext.war $WILDFLYDIR/standalone/deployments/ >> $INSTALLOG 2>&1
#cp -n weasis-i18n.war $WILDFLYDIR/standalone/deployments/ >> $INSTALLOG 2>&1
#sleep 5

if [ -e "weasis_$WEASISVER-1_amd64.deb" ]; then
    echo -e "$SY  weasis-ext.war already downloaded, skipping download... $SD"
else
    echo -e "$SG  Downloading weasis_$WEASISVER-1_amd64.deb  ... $SD"
    $WGET https://sourceforge.net/projects/dcm4che/files/Weasis/$WEASISVER/weasis_$WEASISVER-1_amd64.deb/download
   mv download weasis_$WEASISVER-1_amd64.deb
fi
dpkg -i weasis_$WEASISVER-1_amd64.deb

# Find latest version available for weasis-pacs-connector #
echo -ne "\n $SG Looking for latest version of weasis-pacs-connector ... $SD"
PACSCONVER=`lynx -dump https://sourceforge.net/projects/dcm4che/files/Weasis/weasis-pacs-connector/ | grep weasis-pacs-connector | grep files | grep Weasis | sed -e 's/^.*weasis-pacs-connector\///' -e 's/\/.*//' |head -1`
echo -e "(Found weasis-pacs-connector $PACSCONVER)"
# Install weasis-pacs-connector
if [ -e "weasis-pacs-connector.war" ]; then
    echo -e " $SY Weasis pacs connector already downloaded, skipping download... $SD"
else
    echo -e "$SG Downloading Weasis pacs connector $PACSCONVER ... $SD"
    $WGET https://sourceforge.net/projects/dcm4che/files/Weasis/weasis-pacs-connector/$PACSCONVER/weasis-pacs-connector.war /download
    mv download weasis-pacs-connector.war
fi
echo "Installing Weasis pacs connector $PACSCONVER"
rm dicom-dcm4chee-arc.properties
$WGET https://raw.githubusercontent.com/nroduit/weasis-pacs-connector/master/src/main/resources/dicom-dcm4chee-arc.properties
cat dicom-dcm4chee-arc.properties | sed -e 's/arc.wado.url=${server.base.url}\/wado/arc.wado.url=${server.base.url}\/dcm4chee-arc\/aets\/DCM4CHEE\/wado/' -e 's/arc.host=localhost/arc.host='$IPADDR'/' -e 's/DCM4CHEE/'$AET'/g' > $WILDFLYDIR/standalone/configuration/dicom-dcm4chee.properties
rm weasis-pacs-connector.properties
rm log4j.xml
$WGET https://raw.githubusercontent.com/nroduit/weasis-pacs-connector/master/src/main/resources/log4j.xml
$WGET https://raw.githubusercontent.com/nroduit/weasis-pacs-connector/master/src/main/resources/weasis-pacs-connector.properties
cp log4j.xml $WILDFLYDIR/standalone/configuration/
cp weasis-pacs-connector.properties $WILDFLYDIR/standalone/configuration/
cp -n $DOWNLOADSDIR/weasis-pacs-connector.war $WILDFLYDIR/standalone/deployments/ >> $INSTALLOG 2>&1



# Find latest version available for Oviyam #
echo -ne "\n $SG Looking for latest version of Oviyam download... $SD"
OVIYAMVER=`lynx -dump https://sourceforge.net/projects/dcm4che/files/Oviyam/ | grep files | grep -v timeline | grep Oviyam | grep -v web | sed -e 's/^.*Oviyam\///' -e 's/\/.*//' |head -1`
#OVIYAMVER="3.8.0"

echo -e "(Found Oviyam $OVIYAMVER)"
# Install Oviyam
if [ -e "Oviyam-$OVIYAMVER-bin.zip" ]; then
    echo -e "$SY  Oviyam already downloaded, skipping download... $SD"
else
    echo -e "$SG  Downloading Oviyam $OVIYAMVER ... $SD"
    $WGET https://sourceforge.net/projects/dcm4che/files/Oviyam/$OVIYAMVER/Oviyam-$OVIYAMVER-bin.zip/download
    mv download Oviyam-$OVIYAMVER-bin.zip
fi
echo -e "  Installing Oviyam $OVIYAMVER"
unzip -qn Oviyam-$OVIYAMVER-bin.zip
cp -n $DOWNLOADSDIR/Oviyam-$OVIYAMVER-bin/Oviyam-$OVIYAMVER-bin/oviyam2.war $WILDFLYDIR/standalone/deployments/oviyam.war >> $INSTALLOG 2>&1
cp -n Oviyam-$OVIYAMVER-bin/tomcat/* $WILDFLYDIR/standalone/lib/ext/ >> $INSTALLOG 2>&1


### Install and configure ###

#echo -e "\nConverting DCM4CHEE instance to $AET instance.."
#find $WILDFLYDIR/ -type f -exec sed -i "s/DCM4CHEE/$AET/g" {} +

echo -e "\n $SG Creating pacsdb database... $SD"
mysql -uroot <<MYSQL_SCRIPT
create database $PACSDB; 
create user $DBUSER identified with mysql_native_password by '$DBPASS';
grant all privileges on $PACSDB.* to '$DBUSER'@'%' with grant option; 
flush privileges; 
quit
MYSQL_SCRIPT
mysql -uroot -h localhost $PACSDB < $WILDFLYDIR/sql/mysql/create-mysql.sql
mysql -uroot -h localhost $PACSDB < $WILDFLYDIR/sql/mysql/update-5.29-mysql.sql 
echo "MySQL user and database created."

# Configure LDAP
echo -e "\n $SG Creating LDAP database... $SD"
cp -rn $WILDFLYDIR/ldap/schema/* /etc/ldap/schema/
cat <<EOF >/etc/ldap/slapd.conf
# Global Directives:

# Schema and objectClass definitions
include         /etc/ldap/schema/core.schema
include         /etc/ldap/schema/dicom.schema
include         /etc/ldap/schema/dcm4che.schema
include         /etc/ldap/schema/dcm4chee-archive.schema
include         /etc/ldap/schema/dcm4chee-archive-ui.schema


# Where the pid file is put. The init.d script
# will not stop the server if you change this.
pidfile         /var/run/slapd/slapd.pid

# List of arguments that were passed to the server
argsfile        /var/run/slapd/slapd.args

# Read slapd.conf(5) for possible values
loglevel        none

# Where the dynamically loaded modules are stored
modulepath	/usr/lib/ldap
moduleload	back_mdb

# The maximum number of entries that is returned for a search operation
sizelimit 5000

# The tool-threads parameter sets the actual amount of cpu's that is used
# for indexing.
tool-threads 1

#######################################################################
# Specific Backend Directives for mdb:
# Backend specific directives apply to this backend until another
# 'backend' directive occurs
backend		mdb

#######################################################################
# Specific Backend Directives for 'other':
# Backend specific directives apply to this backend until another
# 'backend' directive occurs
#backend		<other>

#######################################################################
# Specific Directives for database #1, of type mdb:
# Database specific directives apply to this databasse until another
# 'database' directive occurs
database        mdb

# The base of your directory in database #1
suffix          <$LDAPROOT>

# rootdn directive for specifying a superuser on the database. This is needed
# for syncrepl.
rootdn          <cn=admin,$LDAPROOT>

#пароль пользователя syncrepl
credentials= $LDAPADMINPW


# Where the database file are physically stored for database #1
directory       /var/lib/ldap

# Indexing options for database #1
index           objectClass eq

# Save the time that the entry gets modified, for database #1
lastmod         on

# Checkpoint the BerkeleyDB database periodically in case of system
# failure and to speed slapd shutdown.
checkpoint      512 30

# The userPassword by default can be changed
# by the entry owning it if they are authenticated.
# Others should not be able to see it, except the
# admin entry below
# These access lines apply to database #1 only
access to attrs=userPassword,shadowLastChange by dn=<cn=admin,$LDAPROOT> write
        by anonymous auth
        by self write
        by * none

# Ensure read access to the base for things like
# supportedSASLMechanisms.  Without this you may
# have problems with SASL not knowing what
# mechanisms are available and the like.
# Note that this is covered by the 'access to *'
# ACL below too but if you change that as people
# are wont to do you'll still need this if you
# want SASL (and possible other things) to work 
# happily.
access to dn.base="" by * read

# The admin dn has full write access, everyone else
# can read everything.
access to *
        by dn=<cn=admin,$LDAPROOT> write
        by * read
EOF



echo -n "$LDAPADMINPW" > ./ldap-admin-pw.txt
chmod 600 ldap-admin-pw.txt
LDAP_ADMIN_HASH=$(slappasswd -h '{SHA}' -T ldap-admin-pw.txt)
cat <<EOF >./newpassword.ldif
dn: olcDatabase={1}mdb,cn=config
changetype: modify
replace: olcRootPW
olcRootPW: $LDAP_ADMIN_HASH
EOF
ldapmodify -H ldapi:// -Y EXTERNAL -f ./newpassword.ldif >> $INSTALLOG 2>&1
rm ./newpassword.ldif
rm ldap-admin-pw.txt

echo -e "  Importing LDAP schema files for OpenLDAP runtime configuration"
cd $WILDFLYDIR/ldap/
cat <<EOF >modify-baseDN.ldif
dn: olcDatabase={1}mdb,cn=config
changetype: modify
replace: olcSuffix
olcSuffix: ${LDAPROOT}
-
replace: olcRootDN
olcRootDN: cn=admin,${LDAPROOT}
-
EOF

ldapmodify -Y EXTERNAL -H ldapi:/// -f ./modify-baseDN.ldif >> $INSTALLOG 2>&1
#cp init-config.ldif init-config.ldif.orig
#cp default-config.ldif default-config.ldif.orig
#cp add-vendor-data.ldif add-vendor-data.ldif.orig
sed -i s/dc=dcm4che,dc=org/$LDAPROOT/ init-config.ldif
sed -i s/dc=dcm4che,dc=org/$LDAPROOT/ default-config.ldif
sed -i s/dc=dcm4che,dc=org/$LDAPROOT/ add-vendor-data.ldif
ldapadd -Q -Y EXTERNAL -H ldapi:/// -f $WILDFLYDIR/ldap/slapd/dicom.ldif >> $INSTALLOG 2>&1
ldapadd -Q -Y EXTERNAL -H ldapi:/// -f $WILDFLYDIR/ldap/slapd/dcm4che.ldif >> $INSTALLOG 2>&1
ldapadd -Q -Y EXTERNAL -H ldapi:/// -f $WILDFLYDIR/ldap/slapd/dcm4chee-archive.ldif >> $INSTALLOG 2>&1
ldapadd -Q -Y EXTERNAL -H ldapi:/// -f $WILDFLYDIR/ldap/slapd/dcm4chee-archive-ui.ldif >> $INSTALLOG 2>&1
ldapadd -x -D cn=admin,$LDAPROOT -w $LDAPADMINPW -f $WILDFLYDIR/ldap/init-baseDN.ldif >> $INSTALLOG 2>&1
ldapadd -x -D cn=admin,$LDAPROOT -w $LDAPADMINPW -f $WILDFLYDIR/ldap/init-config.ldif >> $INSTALLOG 2>&1
#cp default-config.ldif default-config.ldif.tmp
#cat default-config.ldif.tmp | sed -e 's/DCM4CHEE_ADMIN/'$AET'_ADMIN/g' -e 's/DCM4CHEE_TRASH/'$AET'_TRASH/g' -e 's/DCM4CHEE/'$AET'/g' > default-config.ldif
#rm default-config.ldif.tmp
ldapadd -x -D cn=admin,$LDAPROOT -w $LDAPADMINPW -f $WILDFLYDIR/ldap/default-config.ldif >> $INSTALLOG 2>&1
ldapadd -x -D cn=admin,$LDAPROOT -w $LDAPADMINPW -f $WILDFLYDIR/ldap/add-vendor-data.ldif >> $INSTALLOG 2>&1
ldapadd -x -D cn=admin,$LDAPROOT -w $LDAPADMINPW -f $WILDFLYDIR/ldap/weasis.ldif >> $INSTALLOG 2>&1

cat <<EOF >weasis2.ldif
dn: dcmWebAppName=DCM4CHEE,dicomDeviceName=dcm4chee-arc,cn=Devices,cn=DICOM Configuration,dc=dcm4che,dc=org
changetype: modify
add: dcmProperty
dcmProperty: IID_PATIENT_URL=weasis://$dicom:rs --url "http://$MYIP:8080/dcm4chee-arc/aets/$AET/rs" -r "patientID={{patientID}}" --query-ext "&includedefaults=false"
-

dn: dcmWebAppName=DCM4CHEE,dicomDeviceName=dcm4chee-arc,cn=Devices,cn=DICOM Configuration,dc=dcm4che,dc=org
changetype: modify
add: dcmProperty
dcmProperty: IID_STUDY_URL=weasis://$dicom:rs --url "http://$MYIP:8080/dcm4chee-arc/aets/$AET/rs" -r "studyUID={{studyUID}}" --query-ext "&includedefaults=false"

dn: dcmWebAppName=DCM4CHEE,dicomDeviceName=dcm4chee-arc,cn=Devices,cn=DICOM Configuration,dc=dcm4che,dc=org
changetype: modify
add: dcmProperty
dcmProperty: IID_URL_TARGET=_self
EOF
ldapadd -x -D cn=admin,$LDAPROOT -w $LDAPADMINPW -f $WILDFLYDIR/ldap/weasis2.ldif >> $INSTALLOG 2>&1
ldapadd -x -D cn=admin,$LDAPROOT -w $LDAPADMINPW -f $WILDFLYDIR/ldap/$DCMARCVER/update-AS_RECEIVED-5.29.1.ldif >> $INSTALLOG 2>&1
ldapadd -x -D cn=admin,$LDAPROOT -w $LDAPADMINPW -f $WILDFLYDIR/ldap/$DCMARCVER/update-DCM4CHEE-5.29.1.ldif >> $INSTALLOG 2>&1
ldapadd -x -D cn=admin,$LDAPROOT -w $LDAPADMINPW -f $WILDFLYDIR/ldap/$DCMARCVER/update-dev-5.29.1.ldif >> $INSTALLOG 2>&1
ldapadd -x -D cn=admin,$LDAPROOT -w $LDAPADMINPW -f $WILDFLYDIR/ldap/$DCMARCVER/update-storescp-5.29.1.ldif >> $INSTALLOG 2>&1
ldapadd -x -D cn=admin,$LDAPROOT -w $LDAPADMINPW -f $WILDFLYDIR/ldap/$DCMARCVER/update-WORKLIST-5.29.1.ldif >> $INSTALLOG 2>&1
ldapadd -x -D cn=admin,$LDAPROOT -w $LDAPADMINPW -f $WILDFLYDIR/ldap/$DCMARCVER/update-IOCM_REGULAR_USE-5.29.1.ldif >> $INSTALLOG 2>&1

# Restart LDAP-server
echo -e "  Restarting LDAP"
/etc/init.d/slapd restart

# Configure Wildfly

echo -e "\n $SG Configuring Wildfly... $SD"
cp -r $WILDFLYDIR/standalone/configuration/standalone.xml $WILDFLYDIR/standalone/configuration/dcm4chee-arc.xml

cat <<EOF >$WILDFLYDIR/cli/add-data-source-mysql.cli
/subsystem=datasources/jdbc-driver=mysql:add(driver-module-name=com.mysql,driver-name=mysql)
data-source add --name=pacsds --driver-name=mysql --jndi-name=java:/PacsDS \
--connection-url=jdbc:mysql://localhost:3306/$PACSDB \
--user-name=$DBUSER --password=$DBPASS
EOF
cat <<EOF >$WILDFLYDIR/standalone/configuration/dcm4chee-arc/ldap.properties
java.naming.factory.initial=com.sun.jndi.ldap.LdapCtxFactory
java.naming.ldap.attributes.binary=dicomVendorData
java.naming.provider.url=ldap://localhost:389/$LDAPROOT
java.naming.security.principal=cn=admin,$LDAPROOT
java.naming.security.credentials=$LDAPADMINPW
EOF

# Creating start stop scripts
cat <<EOF >$WILDFLYDIR/bin/pacs_start.sh
#!/bin/bash
USERID=`id -u $PACSUSER`
if [ "\$EUID" -ne "\$USERID" ]
    then echo -e "\n $SY Please run as user $PACSUSER $SD \n"
    exit
else
    echo -e "\nStarting Wildfly ..."
    $WILDFLYDIR/bin/standalone.sh -b=0.0.0.0 -bmanagement=0.0.0.0 -c dcm4chee-arc.xml >> $WILDFLYDIR/server.log 2>&1 &
    disown
    sleep 10
    echo -e "\nWildfly started, log is in $WILDFLYDIR/server.log"
fi
EOF
chmod +x $WILDFLYDIR/bin/pacs_start.sh

cat <<EOF >$WILDFLYDIR/bin/pacs_stop.sh
#!/bin/bash
USERID=`id -u $PACSUSER`
if [ "\$EUID" -ne "\$USERID" ]
    then echo -e "\n $SY Please run as user $PACSUSER $SD \n"
    exit
else
    echo -e "\nStopping Wildfly ..."
    $WILDFLYDIR/bin/jboss-cli.sh --connect command=:shutdown
    sleep 10
    for p in `ps -ef | grep wildfly | awk '{print $2}' | tr '\n' ' '`
    do
        kill -9 $p
    done

fi
EOF
chmod +x $WILDFLYDIR/bin/pacs_stop.sh

# Creating dcm4chee sevice
cat <<EOF >$WILDFLYDIR/dcm4chee.service
Description=dcm4chee.service
After=network-online.target
[Service]
WorkingDirectory=$WILDFLYDIR
PIDFile=/var/run/dcm4chee.pid
ExecStart=$WILDFLYDIR/bin/standalone.sh -b=0.0.0.0 -bmanagement=0.0.0.0 -c dcm4chee-arc.xml
KillMode=process
Restart=always
RestartSec=15
StandardOutput=syslog
StandardError=syslog
SyslogIdentifier=dcm4chee
[Install]
WantedBy=multi-user.target
EOF
cp -n $WILDFLYDIR/dcm4chee.service /etc/systemd/system/dcm4chee.service

systemctl enable dcm4chee

#echo -e "\n $SG Setting permissions on files... $SD"
chown -R $PACSUSER:$PACSUSER $WILDFLYDIR/
chmod -R 777 $WILDFLYDIR/

cd /
cd $WILDFLYDIR/bin
source ./add-user.sh -m -u $PACSUSER -p $PACSUSERPASSW

echo -e "\n $SG Starting Wildfly... $SD"
systemctl start dcm4chee
sleep 15
#su - $PACSUSER -c "$WILDFLYDIR/bin/pacs_start.sh" 2> /dev/null
#sleep 15
echo -e "\n $SG Adding datasource to Wildfly... $SD"
$WILDFLYDIR/bin/jboss-cli.sh -c --file=$WILDFLYDIR/cli/add-data-source-mysql.cli >> $INSTALLOG 2>&1
echo -e "\n $SG Adding managed-executor to Wildfly... $SD"
$WILDFLYDIR/bin/jboss-cli.sh -c --file=$WILDFLYDIR/cli/adjust-managed-executor.cli >> $INSTALLOG 2>&1
echo -e "\n $SG Restarting wildfly $SD"
systemctl stop dcm4chee
sleep 10
#su - $PACSUSER -c "$WILDFLYDIR/bin/pacs_stop.sh" 2> /dev/null
#sleep 5

cp  -rn  $DOWNLOADSDIR/dcm4chee-arc-$DCMARCVER-mysql/deploy/* $WILDFLYDIR/standalone/deployments/ >> $INSTALLOG 2>&1

systemctl start dcm4chee
sleep 15
#su - $PACSUSER -c "/usr/local/bin/pacs_start.sh" 2> /dev/null
#sleep 15
echo -e "\n\n $SG ######### Installation complete ######### $SD"
echo -e "Wildfly Console: http://$IPADDR:9990/ login with Username: $PACSUSER, Password: $PACSUSERPASSW."
echo -e "\nTo access the web interface go to:  http://$IPADDR:8080/dcm4chee-arc/ui2" 
echo -e "\nReboot is required"


