#! /bin/sh

SSHVER="openssh-9.7p1" &&
OLDVER=`ssh -V 2>&1 | cut -d , -f 1 | cut -d _ -f 2` &&

## 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&&

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

###########
# 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-ssl-dir=$SSLVER
else
	./configure --prefix=/usr/local/$SSHVER --with-pam
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/* /etc/ssh/ &&

# sshd initd #
cp -rp /root/wellc-src/init-sshd-backup-$OLDVER /etc/init.d/sshd &&

# 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 &&

service sshd start &&
chkconfig sshd on &&
service sshd status
