##----------##
#    Menu    #
##----------##

echo "Ubuntu 18.04 gitea install script."
echo "Domein without www:"
read domain
while true; do
    read -p "Does www.${domain} exist in DNS -> yes/no?" yn
    case $yn in
        [Yy]* ) domainwww=1
        break;;
        [Nn]* ) domainwww=0
        break;;
        * ) echo "choose yes or no.";;
    esac
done
echo "System password:"
read password
echo "Administrator email:"
read email

##----------------##
#    Pre-Config    #
##----------------##

apt install -y software-properties-common
add-apt-repository -y ppa:certbot/certbot
apt update
apt upgrade -y 
apt install -y mysql-server nginx git
timedatectl set-timezone Europe/Amsterdam
sed -i 's/#/vm.swappiness=10/g' /etc/sysctl.conf
sed -i 's/#/vm.vfs_cache_pressure=50/g' /etc/sysctl.conf
sed -i 's/IPV6=yes/IPV6=no/g'   /etc/default/ufw
sed -i "\$a0 3 * * 1 root apt update >/dev/null 2>&1&& apt upgrade -y >/dev/null 2>&1" /etc/crontab
systemctl restart cron
ufw allow OpenSSH
ufw allow 443/tcp
ufw allow 80/tcp
ufw limit ssh
echo "y" | ufw enable

##------------------##
#    MySQL Config    #
##------------------##

# mysql_secure_installation automated
mysqladmin -u root password "$password"
mysql -u root -p"$password" -e "DELETE FROM mysql.user WHERE User='root' AND Host NOT IN ('localhost', '127.0.0.1', '::1')"
mysql -u root -p"$password" -e "DELETE FROM mysql.user WHERE User=''"
mysql -u root -p"$password" -e "DELETE FROM mysql.db WHERE Db='test' OR Db='test\_%'"
mysql -u root -p"$password" -e "SELECT user,authentication_string,plugin,host FROM mysql.user;"
mysql -u root -p"$password" -e "ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY '"$password"';"
mysql -u root -p"$password" -e "FLUSH PRIVILEGES;"
mysql -u root -p"$password" -e "SELECT user,authentication_string,plugin,host FROM mysql.user;"

rm /etc/mysql/my.cnf
cat > /etc/mysql/my.cnf <<- "EOF"
# - "/etc/mysql/my.cnf" to set global options,
[mysqld_safe]
socket		= /var/run/mysqld/mysqld.sock
nice		= 0

[mysqld]
user		= mysql
pid-file	= /var/run/mysqld/mysqld.pid
socket		= /var/run/mysqld/mysqld.sock
port		= 3306
basedir		= /usr
datadir		= /var/lib/mysql
tmpdir		= /tmp
lc-messages-dir	= /usr/share/mysql
skip-external-locking

innodb_buffer_pool_size = 1G # (adjust value here, 50%-70% of total RAM)
innodb_log_file_size = 256M
innodb_flush_log_at_trx_commit = 1 # may change to 2 or 0
innodb_flush_method = O_DIRECT
bind-address		= 127.0.0.1
key_buffer_size		= 16M
max_allowed_packet	= 16M
thread_stack		= 192K
thread_cache_size       = 8
myisam-recover-options  = BACKUP
#max_connections        = 100
#table_open_cache       = 64
#thread_concurrency     = 10
query_cache_limit	= 1M
query_cache_size        = 16M
log_error = /var/log/mysql/error.log
expire_logs_days	= 10
max_binlog_size   = 100M
EOF

db_pass=$(date +%s|sha256sum|base64|head -c 32)
mysql -u root -p"$password" -e "CREATE DATABASE "giteadb" DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci;"
mysql -u root -p"$password" -e "GRANT ALL ON "giteadb".* TO '"gitea"'@'localhost' IDENTIFIED BY '"$db_pass"';"
mysql -u root -p"$password" -e "FLUSH PRIVILEGES;"
echo $db_pass > ~/db-pass.txt

##------------------##
#    Nginx Config    #
##------------------##   

cat <<EOF > /etc/nginx/sites-available/"$domain"
server {
    server_name git.ictmaatwerk.com;
    client_max_body_size 40M;
    listen 80 ;

    location / {
        proxy_pass http://localhost:3000;
    }
    
    location /.well-known {
        alias /var/www/git.ictmaatwerk.com/.well-known;
    }

    
}
EOF
ln -s /etc/nginx/sites-available/"$domain" /etc/nginx/sites-enabled/
mkdir -p /var/www/"$domain"/html
chmod -R 755 /var/www
systemctl restart nginx
##-------------##
#    Certbot    #
##-------------##
apt install -y python-certbot-nginx
if [ $domainwww = 1 ]; then
    certbot --nginx -n -d "$domain" -d "www.$domain" -m "$email" --hsts --redirect --no-eff-email --agree-tos

elif [ $domainwww = 0 ]; then
    certbot --nginx -n -d "$domain" -m "$email" --hsts --redirect --no-eff-email --agree-tos
fi  


debconf-set-selections <<< "postfix postfix/mailname string $domain"
debconf-set-selections <<< "postfix postfix/main_mailer_type string 'Internet Site'"
apt install -y mailutils
sed -i 's/#inet_interfaces = all/inet_interfaces = loopback-only/g' /etc/postfix/main.cf
sed -i 's/mydestination/#mydestination/g' /etc/postfix/main.cf
sed -i 's/relayhost =/mydestination = '$domain', localhost.'$domain', '$domain'/g' /etc/postfix/main.cf
cat <<EOF > /etc/aliases
# See man 5 aliases for format
postmaster:    root
root:          $email
EOF
newaliases


##-----------##
#    gitea    #
##-----------##
wget https://dl.gitea.io/gitea/1.7.0/gitea-1.7.0-linux-amd64 -O gitea 
chmod +x gitea

adduser \
   --system \
   --shell /bin/bash \
   --gecos 'Git Version Control' \
   --group \
   --disabled-password \
   --home /home/git \
   git
   
mkdir -p /var/lib/gitea/{custom,data,log}
chown -R git:git /var/lib/gitea/
chmod -R 750 /var/lib/gitea/
mkdir /etc/gitea
chown root:git /etc/gitea
chmod 770 /etc/gitea   
mv gitea /usr/local/bin/gitea

cat <<EOF > /etc/systemd/system/gitea.service
[Unit]
Description=Gitea (Git with a cup of tea)
After=syslog.target
After=network.target
After=mysqld.service
#After=postgresql.service
#After=memcached.service
#After=redis.service

[Service]
# Modify these two values and uncomment them if you have
# repos with lots of files and get an HTTP error 500 because
# of that
###
#LimitMEMLOCK=infinity
#LimitNOFILE=65535
RestartSec=2s
Type=simple
User=git
Group=git
WorkingDirectory=/var/lib/gitea/
ExecStart=/usr/local/bin/gitea web -c /etc/gitea/app.ini
Restart=always
Environment=USER=git HOME=/home/git GITEA_WORK_DIR=/var/lib/gitea
# If you want to bind Gitea to a port below 1024 uncomment
# the two values below
###
#CapabilityBoundingSet=CAP_NET_BIND_SERVICE
#AmbientCapabilities=CAP_NET_BIND_SERVICE

[Install]
WantedBy=multi-user.target

EOF

echo certbot --nginx -n -d "$domain" -m "$email" --hsts --redirect --no-eff-email --agree-tos > activatessl.sh
echo "Please put config here: /etc/gitea/app.ini"
echo "then run: systemctl enable gitea && systemctl start gitea"
echo "if service starts then reboot the system to finsh the installation"