#! /bin/sh

SSHVER="openssh-9.7p1"

## Check SSL
if [ `grep -r "/usr/local/openssl" /etc/ld.so.conf* | wc -l` -eq 1 ]; then
        SSLVER=`grep -r "/usr/local/openssl" /etc/ld.so.conf* | awk -F: '{print $2}' | cut -d / -f 1-4`
        IsSSL=1
else
        IsSSL=0
fi

## CheckDir
if [ -d /usr/local/$SSHVER ]; then
        echo " $SSHVER is aleady installed "
        exit 1
fi

yum install -y pam-devel zlib-devel openssl-devel gcc libedit-devel &&

cp -rp /etc/ssh/ /root/wellc-src/ssh-backup &&
cp /etc/pam.d/sshd /root/wellc-src/pam-sshd-backup &&

###########
# openssh #
###########
cd /root/wellc-src/ &&

tar zxvf $SSHVER.tar.gz &&

cd $SSHVER/ &&
if [ $IsSSL -eq 1 ]; then
	./configure --prefix=/usr/local/$SSHVER --with-pam --with-libedit --with-ssl-dir=$SSLVER
else
	./configure --prefix=/usr/local/$SSHVER --with-pam --with-libedit
fi &&

make &&
make install &&

## Delete installed openss
if [ `rpm -qa | grep openssh-server | wc -l` -eq 1 ]; then
        rpm -e --nodeps openssh openssh-clients openssh-server
fi &&

ln -Tfs /usr/local/$SSHVER /usr/local/openssh &&
ln -Tfs /usr/local/openssh/bin/ssh /usr/bin/ssh &&
ln -Tfs /usr/local/openssh/bin/scp /usr/bin/scp &&
ln -Tfs /usr/local/openssh/bin/sftp /usr/bin/sftp &&
ln -Tfs /usr/local/openssh/sbin/sshd /usr/sbin/sshd &&
ln -Tfs /usr/local/openssh/bin/ssh-add /usr/bin/ssh-add &&
ln -Tfs /usr/local/openssh/bin/ssh-agent /usr/bin/ssh-agent &&
ln -Tfs /usr/local/openssh/bin/ssh-keygen /usr/bin/ssh-keygen &&
ln -Tfs /usr/local/openssh/bin/ssh-keyscan /usr/bin/ssh-keyscan &&

rm -rf /etc/ssh &&
ln -Tfs /usr/local/openssh/etc /etc/ssh &&


# PAM Copy #
cp /root/wellc-src/pam-sshd-backup /etc/pam.d/sshd &&

# backup sshd_config Copy #
c\p -p /root/wellc-src/ssh-backup/sshd_config  /etc/ssh/sshd_config &&

# sshd systemd #
echo "[Unit]
Description= SSH Server

[Service]
ExecStart=/usr/local/$SSHVER/sbin/sshd -D \$OPTIONS
ExecReload=/bin/kill -HUP \$MAINPID
KillMode=process
Restart=on-failure
RestartSec=10

[Install]
WantedBy=multi-user.target" > /usr/lib/systemd/system/sshd.service &&
chmod 644 /usr/lib/systemd/system/sshd.service &&


# edit sshd_config #
sed -i -e s/^GSSAPIAuthentication\ yes/\#GSSAPIAuthentication\ yes/g /etc/ssh/sshd_config
sed -i -e s/^GSSAPICleanupCredentials\ no/\#GSSAPICleanupCredentials\ no/g /etc/ssh/sshd_config

sed -i -e s/Subsystem/\#Subsystem/g /etc/ssh/sshd_config &&
sed -i -e "`grep -n ^#Subsystem /etc/ssh/sshd_config | awk -F: '{print $1}'` i\Subsystem       sftp    /usr/local/$SSHVER/libexec/sftp-server" /etc/ssh/sshd_config &&
systemctl daemon-reload &&
systemctl start sshd &&
systemctl enable sshd &&
systemctl status sshd
