#!/bin/bash

HOST="${1:-vertexf.top}"
SCRIPT_NAME="$(basename "$0")"

check_step() {
    if [ $1 -ne 0 ]; then
        echo
        echo "=========================================="
        echo "ERROR: $2"
        echo "HOST = ${HOST}"
        echo "Current directory: $(pwd)"
        echo "=========================================="
        echo
        exit 1
    fi
}

echo "===== Task 6 automation started ====="
echo "HOST = ${HOST}"
echo "Working directory: $(pwd)"

echo "===== Cleaning old experiment files (keeping task6_verify.c, task6_verify, and this script) ====="
find . -maxdepth 1 -type f \
  ! -name 'task6_verify.c' \
  ! -name 'task6_verify' \
  ! -name "${SCRIPT_NAME}" \
  -delete
check_step $? "Failed to clean old files."

echo "===== Step 1: Download certificate chain ====="
openssl s_client -connect "${HOST}:443" -showcerts </dev/null 2>/dev/null | tee chain_raw.txt
check_step $? "Failed to download certificate chain."

echo "===== Step 2: Check certificate count ====="
grep -n "BEGIN CERTIFICATE" chain_raw.txt
CERT_COUNT=$(grep -c "BEGIN CERTIFICATE" chain_raw.txt)
echo "Certificate count = ${CERT_COUNT}"

if [ "${CERT_COUNT}" -lt 2 ]; then
    echo "ERROR: Less than 2 certificates found in chain_raw.txt"
    echo "This experiment needs c0.pem and c1.pem."
    exit 1
fi

echo "===== Step 3: Extract c0.pem and c1.pem ====="
awk 'BEGIN{n=0} /BEGIN CERTIFICATE/{n++} n==1{print} /END CERTIFICATE/{if(n==1) exit}' chain_raw.txt > c0.pem
check_step $? "Failed to extract c0.pem."

awk 'BEGIN{n=0} /BEGIN CERTIFICATE/{n++} n==2{print} /END CERTIFICATE/{if(n==2) exit}' chain_raw.txt > c1.pem
check_step $? "Failed to extract c1.pem."

test -s c0.pem
check_step $? "c0.pem is empty or missing."

test -s c1.pem
check_step $? "c1.pem is empty or missing."

echo "===== Step 4: Show subject/issuer ====="
openssl x509 -in c0.pem -noout -subject -issuer | tee c0_info.txt
check_step $? "Failed to parse c0.pem."

openssl x509 -in c1.pem -noout -subject -issuer | tee c1_info.txt
check_step $? "Failed to parse c1.pem."

echo "===== Step 5: Check signature algorithm ====="
openssl x509 -in c0.pem -text -noout | grep "Signature Algorithm" | tee sigalg.txt
check_step $? "Failed to read signature algorithm from c0.pem."

if ! grep -q "sha256WithRSAEncryption" sigalg.txt; then
    echo
    echo "=========================================="
    echo "ERROR: ${HOST} is NOT using sha256WithRSAEncryption."
    echo "This Task 6 script only supports RSA PKCS#1 v1.5 + SHA-256."
    echo "Please choose another RSA-based certificate, for example vertexf.top."
    echo "=========================================="
    echo
    exit 1
fi

echo "===== Step 6: Extract modulus and exponent ====="
openssl x509 -in c1.pem -noout -modulus | cut -d= -f2 > modulus.hex
check_step $? "Failed to extract modulus from c1.pem."

openssl x509 -in c1.pem -text -noout | sed -n 's/.*Exponent: \([0-9][0-9]*\).*/\1/p' > exponent.dec
check_step $? "Failed to extract exponent from c1.pem."

test -s modulus.hex
check_step $? "modulus.hex is empty."

test -s exponent.dec
check_step $? "exponent.dec is empty."

echo "Exponent:"
cat exponent.dec

echo "===== Step 7: Extract signature ====="
openssl x509 -in c0.pem -text -noout \
| awk '
/Signature Algorithm:/ {capture=1; block=""; next}
capture {block = block $0 "\n"}
END {printf "%s", block}
' \
| tr -cd '0-9A-Fa-f' > signature.hex
check_step $? "Failed to extract signature.hex."

test -s signature.hex
check_step $? "signature.hex is empty."

echo "signature.hex length:"
wc -c signature.hex
echo "modulus.hex length:"
wc -c modulus.hex

echo "===== Step 8: Extract certificate body ====="
openssl asn1parse -i -in c0.pem -strparse 4 -out c0_body.bin -noout
check_step $? "Failed to extract c0_body.bin."

test -s c0_body.bin
check_step $? "c0_body.bin is empty."

echo "===== Step 9: Compute SHA-256 ====="
sha256sum c0_body.bin | tee body_sha256.txt
check_step $? "Failed to compute SHA-256."

if [ ! -f task6_verify.c ]; then
    echo "ERROR: task6_verify.c not found in current directory."
    exit 1
fi

echo "===== Step 10: Compile verifier ====="
gcc task6_verify.c -lcrypto -o task6_verify
check_step $? "Compilation failed."

echo "===== Step 11: Run verifier ====="
./task6_verify c0_body.bin signature.hex modulus.hex "$(cat exponent.dec)" | tee verify_result.txt
check_step $? "Verification program failed."

echo
echo "===== SUCCESS ====="
echo "All steps completed."
echo "Generated files:"
ls -1
