#!/bin/bash
echo -e " \e[38;5;239m                  \e[38;5;242m__              \e[38;5;245m__          \e[38;5;247m__ \e[38;5;249m__\e[0m"
echo -e " \e[38;5;239m     _____ \e[38;5;241m_____ \e[38;5;242m/ /\e[38;5;243m____   \e[38;5;244m_____ \e[38;5;245m/ /_ \e[38;5;246m____ _ \e[38;5;247m/ /\e[38;5;249m/ /\e[0m"
echo -e " \e[38;5;239m    / ___/\e[38;5;241m/ ___/\e[38;5;242m/ /\e[38;5;243m/ __ \ \e[38;5;244m/ ___/\e[38;5;245m/ __/\e[38;5;246m/ __  /\e[38;5;247m/ /\e[38;5;249m/ / \e[0m"
echo -e " \e[38;5;239m   (__  )\e[38;5;241m(__  )\e[38;5;242m/ /\e[38;5;243m/ / / /\e[38;5;244m(__  )\e[38;5;245m/ /_ \e[38;5;246m/ /_/ /\e[38;5;247m/ /\e[38;5;249m/ /  \e[0m"
echo -e " \e[38;5;239m  /____/\e[38;5;241m/____/\e[38;5;242m/_/\e[38;5;243m/_/ /_/\e[38;5;244m/____/ \e[38;5;245m\__/ \e[38;5;246m\__,_/\e[38;5;247m/_/\e[38;5;249m/_/   \e[0m"
echo -e "\e[39msslnstall is a script for automatic installs SSLs with the Comodo Reseller API & cPanel's UAPI." 
printf "created by sadhana@scry.online. thanks to willp & danielwa/larryw. \n\n • Ticket Information collected from the locked ticket SSL queue page. \n  ( for example see:hiyh.tk/ticket.png or copy hiyh.tk/ssltemplate ) \n\n • A dedicated IP should have been assigned by now if this is site is on shared hosting. \n  (you can try running account-review) \n\n • ENSURE THE DOMAIN'S DNS POINTS TO THIS SERVER! \n\n • Be logged in as the cPanel user and go to the domain's document root. \n\n • Have the Comodo Reseller username / password ready. \n\n"

###"    This program is free software: you can redistribute it and/or modify\n"
###"    it under the terms of the GNU General Public License as published by\n"
###"    the Free Software Foundation, either version 3 of the License, or\n"
###"    (at your option) any later version.\n"
###
###"    This program is distributed in the hope that it will be useful,\n"
###"    but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
###"    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n"
###"    GNU General Public License for more details.\n"
###
###"    http://www.gnu.org/licenses/\n"

#Parse ticket information for Certificate Name:, City:, State:, Country:, Company Name:, and Email 1:
printf "Paste your SSL ticket information: \n"
IFS= read -d '' -n 1 tick 
while IFS= read -d '' -n 1 -t 2 c 
do
    tick+=$c 
done


printf "\n\nProcessing ticket variables" && sleep 1 && printf "." && sleep 1 && printf "." && sleep 1 && printf ". \n"
printf "$tick" > ticket
	domain=$(cat ticket |grep -oP "(?<=Certificate Name:)(.*)" | awk '{print $1}')
		if [ -z "$domain" ]
			then
					echo -e "\e[31mError: \e[0mNo domain was matched in provided ticket template, please verify ticket has valid information"
				exit 0
		fi
	city=$(cat ticket |grep -oP "(?<=City:)(.*)" | awk '{print $1,$2,$3}')
		if [ -z "$city" ]
			then
					echo -e "\e[31mError: \e[0mNo city was matched in provided ticket template, please verify ticket has valid information"
				exit 0
		fi
	state=$(cat ticket |grep -oP "(?<=State:)(.*)" | awk '{print $1,$2}')
		if [ -z "$state" ]
			then
					echo -e "\e[31mError: \e[0mNo state was matched in provided ticket template, please verify ticket has valid information"
				exit 0
		fi
	country=$(cat ticket |grep -oP "(?<=Country:)(.*)" | awk '{print $1,$2}') 
		if [ -z "$country" ]
			then
					echo -e "\e[31mError: \e[0mNo country was matched in provided ticket template, please verify ticket has valid information"
				exit 0
		fi
	co=$(cat ticket |grep -oP "(?<=Company Name:)(.*)" | awk '{print $1,$2,$3}')
		if [ -z "$co" ]
			then
					echo -e "\e[31mError: \e[0mNo company/organization name was matched in provided ticket template, please verify ticket has valid information"
				exit 0
		fi
	email=$(cat ticket |grep -oP "(?<=Email:)(.*)" | awk '{print $1}')

#Remove www. from domain names including it to set a domain variable.
wwww=$(cat ticket |grep -oP "(?<=www.)(.*)" )
	if grep -q www. <<<$domain;
		then
		domain=$(printf "$wwww")
	fi
www="www."$domain
maildot="mail."$domain

	printf "Domain: $domain \n" 
	printf "City: $city \n"
	printf "State: $state \n"
	printf "Country: $country \n"
	printf "Company/Organization Name: $co \n"
	printf "Email: $email \n"

#Generate an SSL key for domain using UAPI with logging to key.log
uapi SSL generate_key $domain 2048 > key.log
printf "\nGenerating SSL Key." && sleep 1 && printf "." && sleep 1 && printf ". \n"
keyid=$(cat key.log |grep -oP "(?<=id:\s)(.*)" | awk '{print $1}')
rawkey=$(cat key.log |grep -oP "(?<=text:\s)(.*)" )
key=$(printf "$rawkey" | tr -d '"' )
if grep -qoP "(?<=errors: ~)(.*)" key.log
	 then 
			echo -e "\e[32mSuccessful SSL Key Generation!\e[0m"
	 else 
			echo -e "\e[31mError:\e[0m"
			cat key.log |grep -oP "(?<= - \")(.*)(?=\")"
			echo -e "\e[93mPotential error while generating SSL Key with UAPI, check key.log or ticket for more details.\e[0m"
#		 exit 0
fi
		echo -e "\e[1mKey Id: \e[0m $keyid"
		echo -e "\e[1mKey: \e[0m"
	printf "\n$key \n\n"

#Generate a CSR for ticket variables using UAPI with logging to crt.log
uapi SSL generate_csr domains="$domain,$www,$maildot" countryName=US stateOrProvinceName="$state" localityName="$city" organizationName="$co" key_id="$keyid" > csr.log
printf "\nGenerating Certificate Signing Request" && sleep 1 && printf "." && sleep 1 && printf "." && sleep 1 && printf ". \n"
rawcsr=$(cat csr.log |grep -oP "(?<=text:\s)(.*)" )
csr=$(printf "$rawcsr" | tr -d '"' )
if grep -qoP "(?<=errors: ~)(.*)" csr.log
	then 
			echo -e "\e[32mSuccessful CSR Generation!\e[0m"
	else 
			echo -e "\e[31mError: \e[0m" 
			cat csr.log |grep -oP "(?<= - \")(.*)(?=\")"
			echo -e "\e[93mPotential error while generating Certificate Signing Request (CSR) with UAPI, check csr.log or key.log for more details. \e[0m"
#		exit 0
fi
		echo -e "\e[1mCSR: \e[0m" 
	printf -- "\n$csr \n\n"

#Collect Comodo Login Credentials
echo -e "\e[1mComodo Login \e[0m"
	read -ep "Comodo Username: " comodosn
				if [ -z "$comodosn" ]
					then
						echo ""
						echo -e "\e[93mNo username detected. Please try one more time. \e[0m"
						unset comodosn
						read -ep "Comodo Username: " comodosn
				fi
	read -sp "Comodo Password: " compass
				if [ -z "$compass" ]
					then
						echo ""
						echo -e "\e[93mNo password detected. Please try one more time after stopping to verify the password. \e[0m"
						unset compass
						read -sp "Comodo Password: " compass
				fi
echo ""
read -ep "Press the Enter key to generate DCV links & submit order to Comodo." null

#Rename .htaccess files to .htaccess.bak for preventing redirects during domain verification
find . -type f -name ".htaccess" -exec mv {} {}.bak \;

# Convert CSR and generate hashes for DCV
echo "$csr" | tr -d '"' > $domain.csr
openssl req -in $domain.csr -out $domain.der -outform DER
openssl dgst -sha256 $domain.der > hashes
openssl dgst -md5 $domain.der >> hashes
md5=$(grep -oP "(?<=MD5\($domain.der\)\=\s)(.*)" < hashes | tr '[a-z]' '[A-Z]')
sha=$(grep -oP "(?<=SHA256\($domain.der\)\=\s)(.*)" < hashes | tr '[a-z]' '[A-Z]')
	echo -e "\e[1mMD5: \e[0m$md5"
	echo -e "\e[1mSHA: \e[0m$sha"
mkdir -p .well-known/pki-validation/ 
cat > .well-known/pki-validation/$md5.txt <<DCV
$sha
comodoca.com
DCV
pwd=$(pwd) && echo -e "\e[1mDCV File: \e[0m$pwd/.well-known/pki-validation/$md5.txt"
	cat .well-known/pki-validation/$md5.txt
dcv="http://$domain/.well-known/pki-validation/$md5.txt"
printf "\nCheck the following verification link: \n\n$dcv\n\nIf nothing shows at the verification link, recheck that domain points here and that .htaccess redirects aren't present in a higher directory. \n"

#Login to Comodo and submit CSR request for basic SSL certificate
cat > autoapply.php << _AUTOAPPLY_
		<?php
		\$postVars = array (
		'loginName' => '$comodosn',
		'loginPassword' => '$compass',
		'product' => 488, // ComodoSSL multi-domain certificate
		'years' => 1,
		'csr' => '$csr',
		'serverSoftware' => 31,
		'domainNames' =>  '$domain,$www',
		'primaryDomainName' =>  '$domain',
		'dcvMethod' =>  'HTTP_CSR_HASH',
		'isCustomerValidated' => 'N',
		);
		\$postVars = http_build_query (\$postVars);
		\$apiURL = 'https://secure.comodo.net/products/!AutoApplySSL';
		\$curlHandle = curl_init ();
		curl_setopt (\$curlHandle, CURLOPT_URL, \$apiURL);
		curl_setopt (\$curlHandle, CURLOPT_POST, 1);
		curl_setopt (\$curlHandle, CURLOPT_SSL_VERIFYPEER, TRUE);
		curl_setopt (\$curlHandle, CURLOPT_RETURNTRANSFER, TRUE);
		curl_setopt (\$curlHandle, CURLOPT_POSTFIELDS, \$postVars);
		\$callResult = curl_exec (\$curlHandle);
		if (!curl_error (\$curlHandle)) {
		curl_close (\$curlHandle);
		\$apiReturn = explode (PHP_EOL, trim (\$callResult));
		print_r (\$apiReturn);
		}
		?>
_AUTOAPPLY_
printf "\nGenerating AutoApplySSL API Package" && sleep 1 && printf "." && sleep 1 && printf "." && sleep 1 && printf ". \n"

#Run autoapply PHP script with logging to autoapply.log, then delete PHP script.
php autoapply.php > autoapply.log
printf "\nSubmitting order to Comodo." && sleep 1 && printf "." && sleep 1 && printf ". \n" && rm -f autoapply.php

#Password Error Checking
if  grep -qoP "\-16" autoapply.log 
	then
		echo -e "\e[31mError: \e[0m"
		cat autoapply.log |grep -oP "(?<=\[1\] \=\> )(.*)"
		printf "\nRenaming .htaccess files back to normal and closing.\n"
	find . -type f -name "*.bak" -exec sh -c 'mv -f $0 ${0%.bak}' {} \; && unset compass && exit 0
fi
 
#Order Validation
order=$(cat autoapply.log |grep -oP "(?<=1\]\s\=\>\s)(.*)" )
if grep -oP '[0-9]{9}' autoapply.log
	then
		echo -e "\e[32mSuccessful Order Placement! \e[0m"
	else 
		echo -e "\e[31mError:  \e[0m"
		cat autoapply.log |grep -oP "(?<=\[1\] \=\> )(.*)"
		echo -e "\e[93mPotential Error collecting order, check autocollect.log or try logging into instantSSL.com as the reseller to check the SSL request. \e[0m"
fi
		echo -e "\e[1mComodo Order: \e[0m" && printf "$order"

printf "\nSleeping for 2 minutes as the domain ownership file verifies with Comodo. Notate the account. \n"
sleep 117 && printf "Waking Up" && sleep 1 && printf "." && sleep 1 && printf "." && sleep 1 && printf ". \n\n"

#Collect SSL certificate and CA Bundle
read -ep "Press Enter to submit CRT collection query to Comodo." null
cat > autocollect.php << _AUTOCOLLECT_
		<?php
		\$postVars = array (
		'loginName' => '$comodosn',
		'loginPassword' => '$compass',
		'orderNumber' => '$order',
		'queryType' => 2,
		'responseType' => 3,
		'responseEncoding' => 0,
		'responseFormat' => 0,
		'showValidityPeriod' => 'Y',
		'showStatusDetails' => 'Y',
		);
		\$postVars = http_build_query (\$postVars);
		\$apiURL = 'https://secure.comodo.net/products/download/CollectSSL';
		\$curlHandle = curl_init ();
		curl_setopt (\$curlHandle, CURLOPT_URL, \$apiURL);
		curl_setopt (\$curlHandle, CURLOPT_POST, 1);
		curl_setopt (\$curlHandle, CURLOPT_SSL_VERIFYPEER, TRUE);
		curl_setopt (\$curlHandle, CURLOPT_RETURNTRANSFER, TRUE);
		curl_setopt (\$curlHandle, CURLOPT_POSTFIELDS, \$postVars);
		\$callResult = curl_exec (\$curlHandle);
		if (!curl_error (\$curlHandle)) {
		curl_close (\$curlHandle);
		parse_str(\$callResult, \$apiReturnArray);
		print_r(\$apiReturnArray);
		}
		?>
_AUTOCOLLECT_
printf "\nGenerating CollectSSL API Package" && sleep 1 && printf "." && sleep 1 && printf "." && sleep 1 && printf ". \n"

#Run autocollect PHP script with logging to autocollect.log, then delete PHP script.
php autocollect.php > autocollect.log
printf "\nSubmitting CRT collection request to Comodo." && sleep 1 && printf "." && sleep 1 && printf ". \n" && rm -f autocollect.php

#CRT Validation
crt=$( printf -- "-----BEGIN CERTIFICATE-----" && collectcrt=$(cat autocollect.log | sed -r 's/] =>//') rawcrt=$(echo $collectcrt |grep -oP "(?<=-----BEGIN_CERTIFICATE-----)(.* )(?=.*-----END.*CERTIFICATE-----)" ) && printf "$rawcrt" |tr '_' '+' |tr " " '\n'  && printf -- "-----END CERTIFICATE-----") 
printf "\nParsing Response." && sleep 1 && printf "." && sleep 1 && printf "." && sleep 1 && printf ". \n"
if [ -z "$rawcrt" ]
	then
			echo -e "\e[31mError: \e[0mCRT not found in response!"
			echo -e "\e[93mPotential error while parsing CollectSSL response, check autocollect.log or autoapply.log for more details. \e[0m"
			printf "If the DCV links work then login to Comodo to search for $order and manually download the .crt/ca_bundle zip for installing the crt manually with cPanel/WHM if verification is active. If the DCV check has failed, rename the .htaccess files between home and the DCV file to disable them. If the hashes still do not show, switch to email verification for the DCV check and use the email provided in the ticket. \n"
			cat autocollect.log
	else
	 	echo -e "\e[32mSuccessful CRT collection! \e[0m"
fi
		echo -e "\e[1mCRT: \e[0m"
	printf -- "\n$crt\n\n"

#Rename .htaccess.bak files back to .htaccess
find . -type f -name "*.bak" -exec sh -c 'mv -f $0 ${0%.bak}' {} \;

#Install CRT using UAPI
urlenckey=$(echo "$key" | perl -MURI::Escape -ne 'chomp;print uri_escape($_),"\n"')
urlenccrt=$(echo "$crt" | perl -MURI::Escape -ne 'chomp;print uri_escape($_),"\n"')
printf "\nURL Encoding Key & CRT." && sleep 1 && printf "." && sleep 1 && printf ". \n" 
uapi SSL install_ssl domain=$domain cert="$urlenccrt" key="$urlenckey" > crt.log
printf "\nInstalling CRT." && sleep 1 && printf "." && sleep 1 && printf "." && sleep 1 && printf ". \n"
if grep -qoP "(?<=errors: ~)(.*)" crt.log
 then 
 		echo -e "\e[32mSuccessful CRT Installation! \e[0m"
 else 
		echo -e "\e[31mError: \e[0m"
		cat crt.log |grep -oP "(?<= - \")(.*)(?=\")"
		printf "\nFailure while installing CRT with UAPI, check autocollect.log and crt.log for more details. \n"
fi

printf "\nScript Complete. Test the SSL: sslshopper.com/ssl-checker.html?hostname=$domain \n"
#rm -f ticket key.log csr.log crt.log "$domain.csr" "$domain.der" t2.log autocollect.log autoapply.log hashes
unset compass
printf "Thanks for using sslnstall! \n"