#!/bin/env bash

# LOG保存先、Logファイル作成ルール
# BaseOS: ubuntu2204
#
# ログディレクトリ作成（既存判定あり）
# rootユーザ作成
# OSアップデート
# locale, Install curl, wget, git, ssl, nginx

THISSH=$(basename "${BASH_SOURCE[0]}")
CURDIR=$(pwd)
VAGRANTDIR="/home/vagrant"
SOURCEDIR=""
TARGETDIR=""
VAR1=$var1
VAR2=$var2
LOGDIR="${VAGRANTDIR}/LOGFILE_provision"
NOWDATE=$(date "+%Y%m%d")
NOWTIMM=$(date "+%H%M")
NOWTIME=$(date "+%H%M%S")
MILISEC=$(date "+%3N")
LOGFILE=${LOGDIR}/${NOWDATE}${LOGTIMM}.log
LOGCNT=0

### RESUME ###
# OS update
# Install middles
#    OpenSSL
#    Nginx
#    MySQL
# Service Startup


##FUNC getdate
#   MODE= none: nowdate nowtime.milisec 20230102 012345.67 ミリ秒あり
#            1: nowdate nowtime 20230102 012345 秒まで。ミリ秒なし
#            2: nowdate nowtimm 20230102 0123   秒なし
#            
#   USEAGE: getdate 2
getdate (){
    NOWDATE=$(date "+%Y%m%d")
    NOWTIMM=$(date "+%H%M")
    NOWTIME=$(date "+%H%M%S")
    MILISEC=$(date "+%3N")

    MODE=$1
    if [ -z $MODE ]; then
        outputdate="$NOWDATE $NOWTIME.$MILISEC"
        return outputdate
    elif [ $MODE -eq 1 ];then
        outputdate="$NOWDATE $NOWTIME"
        return outputdate
    elif [ $MODE -eq 2 ];then
        outputdate="$NOWDATE $NOWTIMM"
        return outputdate
    fi    
}

##FUNC: LOGGER
##      usages: logger 処理内容 ステータス エラーコード
##              logger "100" "FUNC-A run" "INFO" 
##      output: [20221219 183558] [S10010] [START   ] INSTALL nodejs typescript 
##              [20221219 183558] [E90010] [CRITICAL] INSTALL nodejs typescript 
##              [20221219 183558] [E50032] [ERROR   ] INSTALL nodejs typescript xxxxxxxxxxxx
## エラーコードは、
## イニシャル＋4桁番号（３＋２、前半はステータス3桁番号、後半２桁は通番00～99、00=無採番エラー、99=Fatal, critical, panicのエラー、01～95は採番エラー、96～98は予備）
## X＝実行中、E＝エラー、K＝成功、I=インフラエラー、D＝DBエラー、OT＝原因不明
## X=100番台、E＝400、500番台、K＝200番台、I＝800番台、D＝900番台、OT9999
## 100~500はHTTPレスポンス仕様に類似させておく。600～900は独自。
logger () {
    LOGDATE=$(date "+%Y%m%d")
    LOGTIMM=$(date "+%H%M")
    LOGTIME=$(date "+%H%M%S")
    LOGMSEC=$(date "+%3N")
    if [ $LOGCNT -eq 0 ]; then
        echo -e "---------- [${LOGDATE} ${LOGTIME}] --------------------------------------------" >> "${LOGFILE}"
        LOGCNT=1
    fi

    ERRCODE=$(printf "%-6s" "$1")      # エラーコード　100 EXECTing, 200 OK, 300 RETURN, 400 FAUSE, 500 SV-APP ERR, 600,700 TESTING ERROR, 800 INFLA-ERR ,900 DB-ERR
    STEPSTATUS=$(printf "%-8s" "$2")   # 100(INFO, WAIT, SPOOL, DO, RUN, DONE),  200(SUCCESS, OK), 400,500(NG, WARING, ERROR, CRITICAL, PUNIC!, TRUE, FAULSE)  
    RET=""
    RET=$(echo ${RET//\n/})             # 改行を削除
    STEPSUBJECT=$3${RET}                # 処理内容 RETは詳細内容を追加する場合に利用する
    ## Loggins Start
    echo -e "[${LOGDATE} ${LOGTIME}.${MILISEC}] [${ERRCODE}] [\e[31m${STEPSTATUS}\e[m] Logger runing ${STEPSUBJECT}" >> "${LOGFILE}"
    ## エラーチェック
    if [[ $? -ne 0 ]]; then
        STEPSTATUS="ERROR"
        ERRCODE=$?
        echo -e "[${LOGDATE} ${LOGTIME}.${MILISEC}] [${ERRCODE}] [\e[31m${STEPSTATUS}\e[m] ${STEPSUBJECT} " >> "${LOGFILE}"
    fi

    ## エラーコード未設定時は000000とする。
    if [ -z "$ERRCODE" ]; then
        ERRCODE="000000"
    fi
    ## ERROR,CRITICAL,PANIC,NGの時は赤字で出力
    if [ "${STEPSTATUS}" == "ERROR" ] || [ "${STEPSTATUS}" == "CRITICAL" ] || [ "${STEPSTATUS}" == "PUNIC!" ] || [ "${STEPSTATUS}" == "NG" ]; then
        echo -e "[${LOGDATE} ${LOGTIME}.${MILISEC}] [${ERRCODE}] [\e[31m${STEPSTATUS}\e[m] ${STEPSUBJECT} " >> "${LOGFILE}"
    else
        echo "[${LOGDATE} ${LOGTIME}.${LOGMSEC}] [${ERRCODE}] [${STEPSTATUS}] ${STEPSUBJECT} " >> "${LOGFILE}"
    fi
}

##FUNC: CHECKINSTALL
##      usages: checkinstall $ERRCODE     ${STEPSUBJECT}
##              checkinstall エラーコード　処理内容
function chekinstall (){
    RESULT=$(echo $?)
    STEPSUBJECT
    if [[ $RESUTL -ne 0 ]]; then
        echo "[${NOWDATE} ${LOGTIME}] [$ERRCODE] [ERROR   cannot install] ${STEPSUBJECT} " >> "${LOGFILE}"
        echo -e "[${NOWDATE} ${NOWTIME}] [$ERRORCODE] [ \e[31m ABORT\e[m Install and Provisioning, then retry ]" >> "${LOGFILE}"
        exit 1
    else
        echo "[${NOWDATE} ${NOWTIME}] [$ERRCODE] [SUCCESS installed] ${STEPSUBJECT} " >> ${LOGFILE}
    fi
}
## endFunctionRegion

## vagrantfile args vagrantfileから引数を受ける
ARG1=$1
ARG2=$2
logger "X10000" "INFO" "getArgs: ${ARG1} ${ARG2} "

# ログディレクトリ作成処理（あれば処理を行わない）
if [[ ! -d ${LOGDIR} && $(ls -ld ${LOGDIR} | awk '{print $4}') -eq "vagrant" ]]; then
    echo -e "\e[31m [${NOWDATE}${NOWDATE}][START] mkdir LOGFILE directory \e[m"
    sudo mkdir $LOGDIR
    sudo chown vagrant:vagrant ${LOGDIR}
    logger "" "INFO" "make Logdir"
    echo -e "\e[31m [${NOWDATE}${NOWDATE}][SUCCESS] mkdir LOGFILE directory \e[m"
else
    sudo chown vagrant:vagrant "${LOGFILE}"
    logger "" "INFO" "exist LOGFILE directory"
fi

logger "" "SUCCESS" "make Logdir"


# rootユーザPW追加
logger "" "START" "root user pw setting"
echo "root:passw0rd" | sudo chpasswd
logger "" "SUCCESS" "root user pw setting" 


# OSアップデート
echo -e "\e[31m $(cat /etc/os-release | awk 'NR==1 {print $0}') \e[m"
logger "" "START" "OS UPDATE"
sudo apt -y update
RET=$(cat /etc/os-release | awk 'NR==1 {print $0}')
logger "" "SUCCESS" "OS UPDATE ${RET}"

# ロケール設定
logger "" "START" "Locale Settigs" 
sudo apt install -y language-pack-ja
echo 'export LANG=ja_JP.UTF-8' >> ~/.bashrc
echo 'export LANGUAGE="ja_JP:ja"' >> ~/.bashrc
localectl list-locales
sudo localectl set-locale LANG=ja_JP.utf8
RET=$(sudo localectl status)
logger "" "SUCCESS" "Locale ${RET}"


# Curl, wget, ntp/time
logger "" "START" "INSTALL curl, wget, ntp"
sudo apt -y install curl
sudo apt -y install wget
sudo apt -y install ntp
sudo systemctl enable ntpd
echo "NTP=ntp.nict.jp >> "/etc/systemd/timesyncd.conf 
sudo systemctl restart systemd-timesyncd
timedatectl timesync-status
sudo timedatectl set-timezone Asia/Tokyo
RETVER=$(curl -V | awk 'NR==1 {print $0}' ; echo " wget "; wget -V | awk 'NR==1 {print $0}'; echo " ntp "; ntpq -c rv |awk 'NR==2 {print $0}')
logger "" "SUCCESS" "INSTALL ${RETVER}"


# INSTALL：Nodejs、TypeScript
logger "" "START" "INSTALL nodejs typescript"

curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.2/install.sh | bash
sudo apt install -y nodejs
sudo apt install -y npm
npm install -y -g typescript
RET=$(node -v; echo "npm "; npm -v; echo "typescript " ; tsc -v;)
echo -e "${RET}"
logger "" "SUCCESS" "INSTALL nodejs typescript ${RET}"

# INSTALL Git
logger "" "START" "INSTALL GIT"
sudo apt install -y git
git config --global user.name 'sandubuntu22ts'
git config --global user.email 'ts@sandubuntu22'
git config --list
RET=$(git --version)
logger "" "SUCCESS" "INSTALL GIT ${RET}"

# INSTALL OpenSSL
logger "X10000" "START" "INSTALL OPENSSL"

sudo wget https://www.openssl.org/source/openssl-1.1.1s.tar.gz
sudo wget https://www.openssl.org/source/openssl-1.1.1s.tar.gz.asc
gpg -d openssl-1.1.1s.tar.gz.asc
sudo tar xvf openssl-1.1.1s.tar.gz
cd openssl-1.1.1s || exit
sudo ./config
sudo make
sudo make install
## setting ldconfig
if [ ! -d /etc/ld.so.conf.d ]; then
    logger "" "WARN" "Openssl not exist"
    exit 1
else
    sudo touch /etc/ld.so.conf.d/openssl.conf
    echo "/home/vagrant/openssl-1.1.1s/libssl.so.1.1" > /etc/ld.so.conf.d/openssl.conf
fi
## openssl.conf書込みチェック
cat /etc/ld.so.conf.d/openssl.conf | grep libssl.so
if [[ $? -ne 0 ]]; then
    logger "" "WARN" "Openssl not write setting libssl.so"
    exit 1
else
    sudo ldconfig
    ldconfig -p | grep libssl.so
fi
## ldconfig -p にlibssl.soが含まれているかチェック
if [[ $? -ne 0 ]]; then
    logger "" "WARN" "Openssl not reflection libssl.so"
    exit 1
else
    logger "" "SUCCESS" "Openssl reflection setting libssl.so"
fi


# nginxのインストールがなんか違う。
## INSTALL Nginx
logger "X10000" "START" "INSTALL nginx"
sudo apt install -y nginx
## UFW許可
sudo ufw allow 'Nginx HTTP'
## nginx自動起動設定
sudo systemctl enable nginx.service
## RETに、nginxが含まれていること、service開始、ステータス確認
RET=$(sudo systemctl list-unit-files -t service | grep nginx \
sudo systemctl start nginx \
sudo systemctl status nginx | awk 'NR==3 {print $0}')
logger "K20000" "SUCCESS" "INSTALL OPENSSL ${RET}"


## INSTALL apache
# Apacheは選択式にしたいかも。
# sudo apt localinstall -y 

## INSTALL MySQL
# インストールだけでなく、mysql のユーザ設定、簡易DB設置を作っておきたいが
# 本当はdocker, k8s化して外だししておきたい
logger "X10000" "START" "INSTALL MySQL"

sudo apt localinstall -y https://dev.mysql.com/get/mysql80-community-release-el7-2.noarch.rpm
# sudo apt localinstall -y http://dev.mysql.com/get/mysql-community-release-el6-5.noarch.rpm
sudo apt install -y mysql-community-server
sudo apt install -y mysql-community-devel
logger "K20000" "SUCCESS" "INSTALL MySQL"


# mongoDBもインストールしておきたい
# ただこちらもdocker, k8sで外だししたい

logger "K2000" "FINISHED" "PROVISIONING" 