#!/bin/bash
# Changing public_html permission
user="$1"
domain="$2"
ip="$3"
home_dir="$4"
docroot="$5"

FORWARDTO=""
FORWARDTOHTTPS=""

# check main address
file=/home/forward-all.txt
if [ -f "$file" ]; then
    FORWARDTO=$(<$file)
fi
file=/home/$user/conf/web/forward-all.txt
if [ -f "$file" ]; then
    FORWARDTO=$(<$file)
fi
file=/home/forward-$domain.txt
if [ -f "$file" ]; then
    FORWARDTO=$(<$file)
fi
file=/home/$user/conf/web/forward-$domain.txt
if [ -f "$file" ]; then
    FORWARDTO=$(<$file)
fi
# if main address not defined, set it to $ip:8080
if [ -z "$FORWARDTO" ]; then
    FORWARDTO="$ip:8080"
fi

# check https address
file=/home/forward-all-https.txt
if [ -f "$file" ]; then
    FORWARDTOHTTPS=$(<$file)
fi
file=/home/$user/conf/web/forward-all-https.txt
if [ -f "$file" ]; then
    FORWARDTOHTTPS=$(<$file)
fi
file=/home/forward-$domain-https.txt
if [ -f "$file" ]; then
    FORWARDTOHTTPS=$(<$file)
fi
file=/home/$user/conf/web/forward-$domain-https.txt
if [ -f "$file" ]; then
    FORWARDTOHTTPS=$(<$file)
fi
# if https address not defined and http address is $ip:8080, set https address to $ip:8443
if [ -z "$FORWARDTOHTTPS" ] && [ "$FORWARDTO" = "$ip:8080" ]; then
    FORWARDTOHTTPS="$ip:8443"
fi
# if https address still not defined, set it to main address
if [ -z "$FORWARDTOHTTPS" ]; then
    FORWARDTOHTTPS=$FORWARDTO
fi

# replace nginx http conf file:
file=/home/$user/conf/web/$domain.nginx.conf
if [ -f "$file" ]; then
    sed -i "s/FORWARDTO/$FORWARDTO/g" $file
fi

# if there is only http endpoint
file=/home/$user/conf/web/forward-$domain-only-http.txt
if [ -f "$file" ]; then
    file=/home/$user/conf/web/$domain.nginx.ssl.conf
    if [ -f "$file" ]; then
        sed -i "s/https/http/g" $file
    fi
fi

# replace nginx https conf file:
file=/home/$user/conf/web/$domain.nginx.ssl.conf
if [ -f "$file" ]; then
    sed -i "s/FORWARDTO/$FORWARDTOHTTPS/g" $file
fi

exit 0
