#!/bin/sh

app=$1

if [ "$app" = "sso" ]; then
    idpurl=
    while [ -z "$idpurl" ]; do
        if [ $LANG = ja_JP.UTF-8 ]; then
            printf "認証サービスのURL [https://slink.secioss.com]: "
        else
            printf "URL of authentication service [https://slink.secioss.com]: "
        fi
        read idpurl leftover
        if [ -z "$idpurl" ]; then
            idpurl="https://slink.secioss.com"
        fi
    done

    tenant=
    if [ $LANG = ja_JP.UTF-8 ]; then
        printf "テナントID: "
    else
        printf "Tenant ID: "
    fi
    read tenant leftover

    url=
    while [ -z "$url" ]; do
        if [ $LANG = ja_JP.UTF-8 ]; then
            printf "アプリケーションのURL: "
        else
            printf "URL of application: "
        fi
        read url leftover
    done

#    session=
#    while [ -z "$session" ]; do
#        if [ $LANG = ja_JP.UTF-8 ]; then
#            printf "セッションのクッキー名: "
#        else
#            printf "Cookie name of session: "
#        fi
#        read session leftover
#    done

    pwdtype=0
    while [ $pwdtype -lt 1 -o $pwdtype -gt 4 ]; do
        if [ $LANG = ja_JP.UTF-8 ]; then
            printf "サービスプロバイダへのパスワード送信 [1.なし|2.シングルサインオンのパスワード|3.サービス個別のパスワード|4.ランダムパスワード]: "
        else
            printf "Service Provider Password [1.None|2.SSO Password|3.Service Provider Password|4.Random Password]: "
        fi
        read pwdtype leftover
    done

    headers_file=
    if [ $LANG = ja_JP.UTF-8 ]; then
        printf "Live HTTP Headersの出力ファイルから代理認証の設定を行う場合ファイル名を入力して下さい。: "
    else
        printf "Please input file of Live HTTP Headers output if you use it for auto login configuration.: "
    fi
    read headers_file leftover

    if [ -n "$headers_file" ]; then
        input_userid=
        while [ -z "$input_userid" ]; do
            if [ $LANG = ja_JP.UTF-8 ]; then
                printf "ログインしたときのユーザID: "
            else
                printf "User ID in login: "
            fi
            read input_userid leftover
        done
        input_password=
        while [ -z "$input_password" ]; do
            if [ $LANG = ja_JP.UTF-8 ]; then
                printf "ログインしたときのパスワード: "
            else
                printf "Password in login: "
            fi
            read input_password leftover
        done

        PARAMS=`./parse_headers.pl $headers_file $input_userid $input_password`
        alogin_login=`echo $PARAMS | awk '{print $1}'`
        alogin_back=`echo $PARAMS | awk '{print $2}'`
        alogin_userid=`echo $PARAMS | awk '{print $3}'`
        alogin_password=`echo $PARAMS | awk '{print $4}'`
        if [ -z "$alogin_login" -o -z "$alogin_back" -o -z "$alogin_userid" -o -z "$alogin_password" ]; then
            if [ $LANG = ja_JP.UTF-8 ]; then
                printf "ファイル名またはユーザIDまたはパスワードが間違っています。"
            else
                printf "File name or user id or password are invalid."
            fi
            exit 1
        fi
    fi

    url=`echo $url | sed 's#/[^./]+\.[^./]+$#/#'`
    entityid=$url
    rurl=`echo $url | sed 's#/$##'`
    path=`echo $rurl | sed 's#^https*://[^/]*/##'`

    if [ -z $path ]; then
        echo "Invalid url"
        exit 1
    fi

    appname=`echo $path | sed 's#^\([^/]*\)/*.*$#\1#'`

    sync=0
    random=0
    if [ $pwdtype -eq 4 ]; then
        sync=1
        random=1
    fi
    if [ $sync -eq 1 -o $random -eq 1 ]; then
        sync="on"
    else
        sync="0"
    fi

    if [ -n "$tenant" ]; then
#        sed s#\'path#\'$path# ./conf/config.php | sed s#https://slink.secioss.com#$idpurl/$tenant# | sed s/SESSIONNAME/$session/ > /tmp/config.php
        sed s#\'path#\'$path# ./conf/config.php | sed s#https://slink.secioss.com#$idpurl/$tenant# > /tmp/config.php
        mv /tmp/config.php /opt/secioss/share/simplesamlphp/config/config.php

        sed s#https://slink.secioss.com/saml/#$idpurl/saml/# ./conf/saml20-idp-remote.php | sed s#\'https://slink.secioss.com\'#\'$idpurl/$tenant\'# > /tmp/saml20-idp-remote.php
        mv /tmp/saml20-idp-remote.php /opt/secioss/share/simplesamlphp/metadata/saml20-idp-remote.php
    else
#        sed s#\'path#\'$path# ./conf/config.php | sed s#https://slink.secioss.com#$idpurl# | sed s/SESSIONNAME/$session/ > /tmp/config.php
        sed s#\'path#\'$path# ./conf/config.php | sed s#https://slink.secioss.com#$idpurl# > /tmp/config.php
        mv /tmp/config.php /opt/secioss/share/simplesamlphp/config/config.php

        sed s#https://slink.secioss.com/saml/#$idpurl/saml/# ./conf/saml20-idp-remote.php | sed s#\'https://slink.secioss.com\'#\'$idpurl\'# > /tmp/saml20-idp-remote.php
        mv /tmp/saml20-idp-remote.php /opt/secioss/share/simplesamlphp/metadata/saml20-idp-remote.php
    fi

    sed s#https://sp.example.com/path#$entityid# ./conf/saml20-sp-hosted.php > /tmp/saml20-sp-hosted.php
    mv /tmp/saml20-sp-hosted.php /opt/secioss/share/simplesamlphp/metadata/saml20-sp-hosted.php

    sed s#ENTITYID#$entityid# ./conf/metadata-template.xml | sed s#URL#$rurl# > metadata.xml

    sed "s/sync = \".*\"/sync = \"$sync\"/" ./conf/config.ini > /tmp/config.ini
    if [ "$random" -eq 1 ]; then
        echo "encryptpwdattr = \"seciossrandompassword\"" >> /tmp/config.ini
    fi
    mv /tmp/config.ini /opt/secioss/var/www/conf/config.ini

    sed s#path#$path# ./conf/autologin.conf > /tmp/autologin.conf
    mv /tmp/autologin.conf /etc/httpd/conf.d/autologin.conf

    if [ ! -f /opt/secioss/share/simplesamlphp/cert/PublicKey-idp.pem ]; then
        wget --no-check-certificate -P /opt/secioss/share/simplesamlphp/cert/ $idpurl/public/PublicKey-idp.pem >& /dev/null
    fi

    sed "s#^loginurl = .*#loginurl = $rurl/sso/autologin.php?sso_app=$appname#" /opt/secioss/var/www/conf/oauth.conf | sed "s/^sessionname = .*$/sessionname = $session/" > /tmp/oauth.conf
    mv /tmp/oauth.conf /opt/secioss/var/www/conf/oauth.conf

    sed s#path#$path# ./conf/oauth.conf > /tmp/oauth.conf
    mv /tmp/oauth.conf /etc/httpd/conf.d/oauth.conf

    if [ -n "$headers_file" ]; then
        sed s#LOGINURL#$alogin_login# ./conf/sp.ini | sed s#BACKURL#$alogin_back# | sed s/USERID/$alogin_userid/ | sed s/PASSWORD/$alogin_password/ > /tmp/sp.ini
        mv /tmp/sp.ini /opt/secioss/var/www/conf/sp.ini
    fi
elif [ "$app" = "idm" ]; then
    idmurl=
    while [ -z "$idmurl" ]; do
        if [ $LANG = ja_JP.UTF-8 ]; then
            printf "統合ID管理サービスのURL [https://slink.secioss.com]: "
        else
            printf "URL of authentication service [https://slink.secioss.com]: "
        fi
        read idmurl leftover
        if [ -z "$idmurl" ]; then
            idmurl="https://slink.secioss.com"
        fi
    done

    tenant=
    while [ -z "$tenant" ]; do
        if [ $LANG = ja_JP.UTF-8 ]; then
            printf "テナントID: "
        else
            printf "Tenant ID: "
        fi
        read tenant leftover
    done

    admin=
    while [ -z "$admin" ]; do
        if [ $LANG = ja_JP.UTF-8 ]; then
            printf "管理者アカウント名: "
        else
            printf "Account name of administrator: "
        fi
        read admin leftover
    done

    password=
    while [ -z "$password" ]; do
        if [ $LANG = ja_JP.UTF-8 ]; then
            printf "管理者のパスワード: "
        else
            printf "Password of administrator: "
        fi
        read password leftover
    done

    type=1
#    while [ $type -lt 1 -o $type -gt 2 ]; do
#        if [ $LANG = ja_JP.UTF-8 ]; then
#            printf "同期の向き [1.統合ID管理 -> サービス|2.サービス -> 統合ID管理]: "
#        else
#            printf "Direction of synchronization [1.Identity Management -> Service|2.Service -> Identity Management]: "
#        fi
#        read type leftover
#    done

    attrnum=0
    if [ $type -eq 1 ]; then
        service=
        while [ -z "$service" ]; do
            if [ $LANG = ja_JP.UTF-8 ]; then
                printf "サービスID: "
            else
                printf "Service ID: "
            fi
            read service leftover
        done

        while [ $attrnum -lt 1 -o $attrnum -gt 5 ]; do
            if [ $LANG = ja_JP.UTF-8 ]; then
                printf "ユーザIDの属性 [1.ユーザID|2.ユーザID@テナントID|3.メールアドレス|4.社員番号|5.サービス個別のログインID]: "
            else
                printf "Attribute of user id [1.user id|2.user id@tenant id|3.mail address|4.employee number|5.login id of service]: "
            fi
            read attrnum leftover
        done

        pwsync=
#        while [ -z "$pwsync" ]; do
#            if [ $LANG = ja_JP.UTF-8 ]; then
#                printf "パスワード同期 [1.する|2.しない]: "
#            else
#                printf "Password synchronization [1.Yes|2.No]: "
#            fi
#            read pwsync leftover
#        done

        if [ $pwsync -eq 1 ]; then
            dsn=
            while [ -z "$dsn" ]; do
                if [ $LANG = ja_JP.UTF-8 ]; then
                    printf "データベースのDSN: "
                else
                    printf "Database DSN: "
                fi
                read dsn leftover
            done

            dbuser=
            while [ -z "$dbuser" ]; do
                if [ $LANG = ja_JP.UTF-8 ]; then
                    printf "データベースに接続するユーザ: "
                else
                    printf "Database user: "
                fi
                read dbuser leftover
            done

            dbpasswd=
            while [ -z "$dbpasswd" ]; do
                if [ $LANG = ja_JP.UTF-8 ]; then
                    printf "データベースのパスワード: "
                else
                    printf "Database password: "
                fi
                read dbpasswd leftover
            done

            table=
            while [ -z "$table" ]; do
                if [ $LANG = ja_JP.UTF-8 ]; then
                    printf "データベースのテーブル名: "
                else
                    printf "Database table name: "
                fi
                read table leftover
            done

            idcol=
            while [ -z "$idcol" ]; do
                if [ $LANG = ja_JP.UTF-8 ]; then
                    printf "プライマリキーのフィールド名: "
                else
                    printf "Primary field name: "
                fi
                read idcol leftover
            done

            usercol=
            while [ -z "$usercol" ]; do
                if [ $LANG = ja_JP.UTF-8 ]; then
                    printf "ユーザIDのフィールド名: "
                else
                    printf "User ID field name: "
                fi
                read usercol leftover
            done

            passwdcol=
            while [ -z "$passwdcol" ]; do
                if [ $LANG = ja_JP.UTF-8 ]; then
                    printf "パスワードのフィールド名: "
                else
                    printf "Password field name: "
                fi
                read passwdcol leftover
            done

            pwhash=
            while [ -z "$pwhash" ]; do
                if [ $LANG = ja_JP.UTF-8 ]; then
                    printf "パスワードのハッシュ形式: "
                else
                    printf "Pssword hash type: "
                fi
                read pwhash leftover
            done
        fi
    fi

    if [ $type -eq 1 ]; then
        sed s/TENANTID/$tenant/g ./conf/lism-sp.conf | sed s/ADMINID/$admin/ | sed s/ADMINPW/$password/ | sed s/SERVICEID/$service/ | sed s#https://slink.secioss.com#$idmurl# > /tmp/lism-sp.conf
        if [ $attrnum -eq 1 ]; then
            sed "s/ *<!-- id//" /tmp/lism-sp.conf | sed "s/ *id -->//" > /tmp/lism-sp2.conf
            mv /tmp/lism-sp2.conf /tmp/lism-sp.conf
        elif [ $attrnum -ge 3 ]; then
            if [ $attrnum -eq 3 ]; then
                attribute=mail
            elif [ $attrnum -eq 4 ]; then
                attribute=employeeNumber
            elif [ $attrnum -eq 5 ]; then
                attribute="seciossLoginId;x-sys-$service@$tenant"
            fi
            sed "s/ *<!-- attribute//" /tmp/lism-sp.conf | sed "s/ *attribute -->//" | sed s/ATTRIBUTE/$attribute/ > /tmp/lism-sp2.conf
            mv /tmp/lism-sp2.conf /tmp/lism-sp.conf
        fi
        cp /tmp/lism-sp.conf /opt/secioss/etc/lism-sp.conf
        rm /tmp/lism-sp.conf
        sed "s/seciossAllowedService=[^)]*/seciossAllowedService=$service-$tenant/" /opt/secioss/etc/lism.conf | sed "s/seciossAllowedService;x-perm-group=[^)]*/seciossAllowedService;x-perm-group=$service-$tenant/" | sed "s/<constant>.*<\/constant>/<constant>$service-$tenant<\/constant>/" | sed "s/<dsn>.*<\/dsn>/<dsn>$dsn<\/dsn>/" | sed "s/<admin>.*<\/admin>/<admin>$dbuser<\/admin>/" | sed  "s/<passwd>.*<\/passwd>/<passwd>$dbpasswd<\/passwd>/" | sed "s/<table>.*<\/table>/<table>$table<\/table>/" | sed "s/<id><column>.*<\/column>/<id><column>$idcol<\/column>/" | sed "s/<attr name=\"uid\"><column>.*<\/column>/<attr name=\"uid\"><column>$usercol<\/column>/" | sed "s/<attr name=\"userpassword\"><column>.*<\/column>/<attr name=\"userpassword\"><column>$passwdcol<\/column>/" | sed "s/<storage name=\"SQL\" hash=\".*\">/<storage name=\"SQL\" hash=\"$pwhash\">/" > /tmp/lism.conf
        cp /tmp/lism.conf /opt/secioss/etc/lism.conf
        rm /tmp/lism.conf
    else
        sed s/uid%1%2@[^\"]*/uid%1%2@$tenant/ /opt/secioss/etc/lism-idp.conf | sed "s/<basedn>o=[^,]*/<basedn>o=$tenant/" | sed "s/<binddn>uid=[^,]*,ou=People,o=[^,]*/<binddn>uid=$admin@$tenant,ou=People,o=$tenant/" | sed "s/<bindpw>[^<]*/<bindpw>$password/" | sed "s/!(uid=[^)]*/!(uid=$admin/" | sed s#https://slink.secioss.com#$idmurl# > /tmp/lism-idp.conf
        cp /tmp/lism-idp.conf /opt/secioss/etc/lism-idp.conf
        rm /tmp/lism-idp.conf
    fi

    sed s/ADMINID/$admin/ ./conf/lismapi.conf | sed s/ADMINPW/$password/ > /tmp/lismapi.conf
    mv /tmp/lismapi.conf /opt/secioss/var/www/conf/lismapi.conf
elif [ "$app" == "oauth" ]; then
    type=0
    while [ $type -lt 1 -o $type -gt 2 ]; do
        if [ $LANG = ja_JP.UTF-8 ]; then
            printf "データベースの種類 [1.mysql|2.PostgreSQL]: "
        else
            printf "Database type: "
        fi
        read type leftover
    done

    host=
    while [ -z "$host" ]; do
        if [ $LANG = ja_JP.UTF-8 ]; then
            printf "データベースのホスト名: "
        else
            printf "Database host name: "
        fi
        read host leftover
    done

    dbuser=
    while [ -z "$dbuser" ]; do
        if [ $LANG = ja_JP.UTF-8 ]; then
            printf "データベースのユーザ: "
        else
            printf "Database user: "
        fi
        read dbuser leftover
    done

    dbpasswd=
    while [ -z "$dbpasswd" ]; do
        if [ $LANG = ja_JP.UTF-8 ]; then
            printf "データベースのパスワード: "
        else
            printf "Database password: "
        fi
        read dbpasswd leftover
    done

    if [ $type -eq 1 ]; then
        phpdsn="mysql:host=$host;dbname=oauth2"
        perldsn="DBI:mysql:oauth2:$host"
    elif [ $type -eq 2 ]; then
        phpdsn="pgsql:host=$host;dbname=oauth2"
        perldsn="DBI:Pg:dbname=oauth2;host=$host"
    fi

    sed "s/^dsn = .*$/dsn = \"$phpdsn\"/" /opt/secioss/var/www/conf/oauth.conf | sed "s/^dbuser = .*$/dbuser = $dbuser/" | sed "s/^dbpasswd = .*$/dbpasswd = $dbpasswd/" > /tmp/oauth.conf
    mv /tmp/oauth.conf /opt/secioss/var/www/conf/oauth.conf

    sed "s/^oauth_dsn .*$/oauth_dsn $perldsn/" /opt/secioss/var/www/api/lism_restapi.conf | sed "s/^oauth_dbuser .*$/oauth_dbuser $dbuser/" | sed "s/^oauth_dbpasswd .*$/oauth_dbpasswd $dbpasswd/" > /tmp/lism_restapi.conf
    mv /tmp/lism_restapi.conf /opt/secioss/var/www/api/lism_restapi.conf
else
    echo "usage: config.sh sso|idm"
fi
