#!/bin/bash
# Author: Ryan
# Desc: Convert a cm4all to static site.
# State: Work In Progress

if ! [ -f '/usr/bin/httrack' ] ; then
        echo "Installing httrack..."
        yum install -y httrack
        exit 1
fi

if ! [ -f '/etc/wwwacct.conf' ] ; then
        echo "Not a cPanel server, support is limited."
        exit 1
fi


usage()
{
    echo "Usage: $0 [-d domain]"
}

no_args="true"

while getopts "h?d:" opt; do
    case "$opt" in
    h|\?)
        usage
        exit 0
        ;;
    d)  DOMAIN=$OPTARG
        ;;
    *)  usage
        exit
        ;;
    esac
    no_args="false"
done        
[[ "$no_args" == "true" ]] && { usage; exit 1; }

if ! [ "$(id -u)" != "0" ]; then
   USERNAME=$(/scripts/whoowns $DOMAIN)
   USERHOMEDIR="/home/$USERNAME"
   echo "This script must be run as $USERNAME."
   echo "frob su in $USERHOMEDIR"
   exit 1
else
   USERNAME=$(/usr/bin/whoami)
   USERHOMEDIR="/home/$USERNAME"
fi


if [ "${#USERNAME}" == 0 ] ; then
        echo "No username found."
        exit 1
fi

EXPORTDIR="$USERHOMEDIR/public_html_static/"
if [ -d $EXPORTDIR ] ; then
        echo "$EXPORTDIR found, not converting."
        exit 0
fi

# Copy The Site
/usr/bin/httrack http://$DOMAIN -O $EXPORTDIR +*.$DOMAIN/* +*.sites.dedicated.co.za/* +*.dedicated.co.za/* --robots=0 -N100

# Clean Up
rm -f $EXPORTDIR/index.html ; cp $EXPORTDIR/Home/index.html $EXPORTDIR/index.html
find $EXPORTDIR -type d -name index.php -exec rm -rf {} \;

# Create .htaccess file
cat <<EOF > $EXPORTDIR/.htaccess
DirectoryIndex index.html
EOF

find $EXPORTDIR -type f -name '*.html' | while read line ; do
sed -i -e s@'index.php/'@'index.html'@g $line
sed -i -e s@"//sites.dedicated.co.za"@"//$DOMAIN"@g $line
done

echo "Final Steps done manually:"
echo "mv $USERHOMEDIR/public_html/ $USERHOMEDIR/public_html_cm4all/"
echo "rsync -av $EXPORTDIR $USERHOMEDIR/public_html/"
echo "touch public_html_cm4all_exported.txt"
echo "Test the site via http://$DOMAIN/"




