#!/bin/bash
if [ ! "$BASH_VERSION" ] ; then
  echo "Warén Group / Infra / Init"
  echo "This command requires using BASH shell."
  exit 1
fi

if [[ -L "$0" ]]
then
  PWD=$(dirname -- "$(readlink -f -- "$0")")
fi

wxi-args(){
  declare -gAx args
  args=()

  args[0]="$0"

  while [[ $# -gt 0 ]]; do
    case "$1" in
      --*=*)
        key="${1%%=*}"
        value="${1#*=}"
        args["${key#--}"]="$value"
        shift
        ;;

      --*)
        key="$1"
        opt="${key#--}"
        shift
        if [[ $# -gt 0 && "${1}" != -* ]]; then
          args["$opt"]="$1"
          shift
        else
          args["$opt"]=true
        fi
        ;;

      -*=*)
        key="${1%%=*}"
        value="${1#*=}"
        args["${key#-}"]="$value"
        shift
        ;;

      -*)
        key="$1"
        opt="${key#-}"
        shift
        if [[ $# -gt 0 && "${1}" != -* ]]; then
          args["$opt"]="$1"
          shift
        else
          args["$opt"]=true
        fi
        ;;

      *)
        args["$((++pos))"]="${1%%=*}"
        shift
        ;;
    esac
  done
}

wxi-config(){
  declare -gAx config

  WX_HOME=$HOME/.warengroup
  export WX_HOME
  mkdir -p $WX_HOME

  mkdir -p "$WX_HOME/credentials" \
           "$WX_HOME/credentials/ssh" \
           "$WX_HOME/credentials/ssh/eas" \
           "$WX_HOME/credentials/ansible-vault" \
           "$WX_HOME/credentials/ansible-vault/eas" \
           "$WX_HOME/infra/eas/credentials/ssh"

  mkdir -p $HOME/.ssh/keys
  chmod 700 -R $HOME/.ssh/keys
  mkdir -p $HOME/.ssh/multiplex
  chmod 700 -R $HOME/.ssh/multiplex

  find "$WX_HOME" -type d -exec chmod 700 {} +
  find "$WX_HOME" -type f -exec chmod 600 {} +

  case $1 in
    create)
      if [[ ! -f $WX_HOME/config.json ]]
      then
        echo '{}' > $WX_HOME/config.json
      fi
      ;;
    deploy)
      if [[ ! $(jq -e . $WX_HOME/config.json.tmp >/dev/null 2>&1) ]]
      then
        mv $WX_HOME/config.json.tmp $WX_HOME/config.json &> /dev/null
      fi
      wxi-config reload
      ;;
    write)
      jq '.'"$2"' = "'$3'"' $WX_HOME/config.json &> $WX_HOME/config.json.tmp
      wxi-config deploy
      ;;
    erase)
      wxi-config write $2 ""
      ;;
    load)
      while IFS=$'\t' read -r k v; do config["$k"]="$v"; done < <(
        jq -r '
          paths(scalars) as $p
          | "\( $p|map(tostring)|join(".") )\t\( getpath($p) )"
          ' $WX_HOME/config.json
        )
      ;;
    reload)
      wxi-config load
      ;;
    *)
      wxi-config create
      if [[ -n ${args['proxy']} ]]
      then
        wxi-config write proxy "${args['proxy']}"
      fi

      wxi-config load

      PROXY_ARGS=()
      if [[ -n "${config['proxy']}" ]]; then
        PROXY_ARGS=(--proxy "${config['proxy']}")
      fi
      ;;
  esac
}

wxi-init(){
  wx-login
  wxi-header "Init"

  if [[ -n ${args['hostname']} && ${#args['hostname']} -gt 5 ]]
  then
    HOSTNAME="${args['hostname']}.devices.$DOMAIN"
  elif [[ $(hostname -d) ]]
  then
    HOSTNAME=$(hostname --fqdn)
  else
    wxi-content status "Error" "Hostname Required"
    wxi-stop
  fi

  if [[ -n ${args['device-type']} ]]
  then
    if [[ ${args['device-type']} == "server" ]]
    then
      DEVICE_TYPE="Server"
    elif [[ ${args['device-type']} == "workstation" ]]
    then
      DEVICE_TYPE="Workstation"
    else
      wxi-content status "Error" "Device Type Invalid"
      wxi-stop
    fi
  else
    wxi-content status "Error" "Device Type Required"
    wxi-stop
  fi

  wxi-header "Ansible" h3

  wxi-content text* "Dependencies: "
  apt-get update &> /dev/null
  apt-get install -y python3-pip python3-venv jq git curl lsb-release sudo sshpass rsync &> /dev/null
  dnf install -y epel-release &> /dev/null
  dnf install -y python3-pip python3-psutil jq git curl lsb_release &> /dev/null
  wxi-content text "Ready ✔"

  wxi-content text* "Python 3 - Virtual Environment: "
  python3 -m venv /opt/ansible &> /dev/null
  if [[ -d "/opt/ansible" ]]
  then
    wxi-content text "Ready ✔"
  else
    wxi-content text "Failed ✖"
  fi

  wxi-content text* "Ansible: "
  /opt/ansible/bin/pip3 install ansible-core &> /dev/null
  if [[ -f "/opt/ansible/bin/ansible-playbook" ]]
  then
    wxi-content text "Ready ✔"
  else
    wxi-content text "Failed ✖"
  fi

  wxi-content text* "Python3 Libraries - Dependencies: "
  /opt/ansible/bin/pip3 install ansi2html cryptography dnspython hvac jmespath netaddr passlib pexpect xmltodict --upgrade &> /dev/null
  wxi-content text "Ready ✔"

  wxi-content text* "Collections: "
  ln -s /opt/ansible/collections /usr/share/ansible/collections &> /dev/null
  /opt/ansible/bin/ansible-galaxy collection install ansible.mariadb ansible.posix ansible.utils ansible.windows community.crypto community.dns community.docker community.general community.grafana community.hashi_vault community.libvirt community.mongodb community.postgresql community.windows containers.podman freeipa.ansible_freeipa middleware_automation.keycloak -p /usr/share/ansible/collections --upgrade &> /dev/null
  wxi-content text "Ready ✔"

  mkdir -p ~/.ssh/keys &> /dev/null
  curl \
    -H "X-Vault-Token: $TOKEN" \
    -X GET \
    https://$VAULT_DOMAIN/v1/init.sh/data/ssh -s | jq -r '.data.data.privkey' > ~/.ssh/keys/init

  chmod 700 ~/.ssh/keys/init &> /dev/null

  mkdir -p ~/.ansible &> /dev/null

  if [ ! -f ~/.ansible/vars.yml ]
  then
    echo "---" > ~/.ansible/vars.yml
    echo "hostname: $HOSTNAME" >> ~/.ansible/vars.yml
    echo "info:" >> ~/.ansible/vars.yml
    echo "  type: $DEVICE_TYPE" >> ~/.ansible/vars.yml
    echo "config:" >> ~/.ansible/vars.yml
    echo "  identity:" >> ~/.ansible/vars.yml
    echo "    vault:" >> ~/.ansible/vars.yml
    echo "      domain: $VAULT_DOMAIN" >> ~/.ansible/vars.yml
  fi

  GIT_DOMAIN="git.waren.io"
  GIT_PORT="2222"
  GIT_REPOSITORY="warengroup-private/infra"

  export TOKEN

  ANSIBLE_CONFIG=~/.ansible/pull/infra/ansible/ansible.cfg /opt/ansible/bin/ansible-pull -U ssh://git@$GIT_DOMAIN:$GIT_PORT/$GIT_REPOSITORY -d ~/.ansible/pull/infra --accept-host-key --private-key ~/.ssh/keys/init --extra-vars @~/.ansible/vars.yml --inventory ansible/inventories/local ansible/init.yml -t init,legacy

  unset TOKEN
}

wxi-restricted(){
  if [[ -z $1 || $1 == "--user" ]]
  then
    if [[ $USER != "root" ]]
    then
      wxi-content status "Error" "Command Restricted"
      wxi-content text "It's not permitted to execute this command as non privileged user"
      wxi-repeat "\n" 3
      exit 1
    fi
  fi

  if [[ -z $1 || $1 == "--org" ]]
  then
    if [[ -n ${args['org']} ]]
    then
      case ${args['org']} in
          warengroup)
              ORG=warengroup
              ;;
          cwchristerw)
              ORG=cwchristerw
              ;;
          *)
              wxi-content status "Error" "Organization Unsupported"
              wxi-stop
              ;;
      esac
    elif [[ $(hostname -d) == "devices.waren.io" ]]
    then
      ORG=warengroup
    elif [[ $(hostname -d) == "devices.christerwaren.fi" ]]
    then
      ORG=cwchristerw
    fi

    if [[ -n $ORG ]]
    then
      case $ORG in
        warengroup)
          DOMAIN=waren.io
          VAULT_DOMAIN=vault.cwinfo.net
          ORG_HEADER="Warén Group"
          ;;
        cwchristerw)
          DOMAIN=christerwaren.fi
          VAULT_DOMAIN=vault.cwinfo.net
          ORG_HEADER="Christer Warén"
          ;;
        *)
          wxi-content status "Error" "Organization Unsupported"
          wxi-stop
          ;;
      esac
    else
      wxi-content status "Error" "Organization Required"
      wxi-stop
    fi
  fi

  if [[ -z $1 || $1 == "--vault" ]]
  then
    if [[ -z $VAULT_DOMAIN ]]
    then
      wxi-content status "Error" "Vault Unavailable"
      wxi-repeat "\n" 3
      exit 1
    fi

    VAULT_STATUS=$(curl -s -o /dev/null -w "%{http_code}" https://$VAULT_DOMAIN/v1/sys/health)
    if [[ ! $VAULT_STATUS -eq 200 ]]
    then
      wxi-content status "Error" "Vault Offline"
      wxi-repeat "\n" 3
      exit 1
    fi
  fi
}

wxi-start(){
  wxi-header "Warén Group / Infra / Init" h1*

  echo -n "Designed by: "
  wxiLink "Warén Group™" "https://waren.io"
}

wxi-stop (){
  rm -rf /.ssh/keys/init &> /dev/null

  wxi-repeat "\n" 3
  exit 1
}

wxi-content(){
  if [[ $1 == "text" ]]
  then
    echo "$2"
  elif [[ $1 == "text*" ]]
  then
    echo -n "$2"
  elif [[ $1 == "status" ]]
  then
    echo -n "Status: "
    echo "$2 - $3"
  elif [[ $1 == "link" ]]
  then
    echo "$2 - $3"
  fi
}

wxiRed=$(tput setaf 196)
wxiGreen=$(tput setaf 46)
wxiYellow=$(tput setaf 226)
wxiBlue=$(tput setaf 21)
wxiPurple=$(tput setaf 165)
wxiTurquoise=$(tput setaf 14)
wxiPink=$(tput setaf 198)
wxiOrange=$(tput setaf 202)
wxiUnderline=$(tput smul)
wxiBold=$(tput bold)
wxiNormal=$(tput sgr0)

wxiLink() {
  printf '\e]8;;%s\e\\%s\e]8;;\e\\\n' "$2" "$1"
}

wxi-header(){
  if [[ $2 == "h1" ]]
  then
    #wxi-repeat " " $(($(tput cols)/2-${#1}/2))
    echo ""
    echo -n "$wxiBold"
    echo ${1^^}
    echo -n "$wxiNormal"
    echo ""
  fi

  if [[ $2 == "h1*" ]]
  then
    #wxi-repeat " " $(($(tput cols)/2-${#1}/2))
    echo -n "$wxiBold"
    echo ${1^^}
    echo -n "$wxiNormal"
  fi

  if [[ $2 == "h2" || $2 == "" ]]
  then
    #wxi-repeat " " $(($(tput cols)/2-${#1}/2))
    echo ""
    echo -n "$wxiBold"
    echo ">> $1 <<"
    echo -n "$wxiNormal"
  fi

  if [[ $2 == "h3" ]]
  then
    #wxi-repeat " " $(($(tput cols)/2-${#1}/2))
    echo ""
    echo -n "$wxiBold"
    echo "$1"
    echo -n "$wxiNormal"
  fi

  if [[ $2 == "h4" ]]
  then
    #wxi-repeat " " $(($(tput cols)/2-${#1}/2))
    echo ""
    echo -n "$wxiUnderline"
    echo "$1"
    echo -n "$wxiNormal"
  fi
}


wxi-repeat() {
  if [[ $1 == " " ]]
  then
    local str=$1 n=$2 spaces
    printf -v spaces "%*s" $n " "
    printf "%s" "${spaces// /$str}"
  else
    for i in $(seq 1 $2);
    do
        echo -en $1
    done
  fi
}

wx-login(){
  wxi-header "Login"

  if [[ -n ${args['eas']} ]]
  then
    wxi-eas-login
    wxi-eas-token-sign-gen
  fi

  if [[ -z ${args['eas']} || $1 == "vault" ]]
  then
    wxi-restricted

    wxi-header "$ORG_HEADER" h3

    if [[ -n ${args['auth-method']} ]]
    then
      AUTH_METHOD=${args['auth-method']}
    elif [[ -n ${args['token']} || -n ${config['login.token']} ]]
    then
      AUTH_METHOD=token
    elif [[ -n ${args['username']} ]]
    then
      AUTH_METHOD=ldap
    else
      AUTH_METHOD=ldap
    fi

    if [[ -n $AUTH_METHOD ]]
    then
      case $AUTH_METHOD in
        ldap)
          echo -n "Username: "
          if [[ -n ${args['username']} ]]
          then
            USERNAME=${args['username']}
            wxi-content text "$USERNAME"
          else
            read USERNAME
          fi

          echo -n "Password: "
          if [[ -n ${args['password']} ]]
          then
            PASSWORD=${args['password']}
          else
            read -s PASSWORD
          fi

          if [[ -n $PASSWORD ]]
          then
            wxi-content text "****************"
          else
            wxi-content text ""
          fi

          if [[ -z $USERNAME || -z $PASSWORD ]]
          then
            wxi-content status "Error" "Username & Password Required"
            wxi-stop
          fi

          VAULT_LOGIN=$(curl https://$VAULT_DOMAIN/v1/auth/ldap/login/$USERNAME -X POST -d '{ "password": "'$PASSWORD'" }' -s | jq -r '.auth.client_token')
          if [[ -z $VAULT_LOGIN || ${#VAULT_LOGIN} -lt 95 || ${#VAULT_LOGIN} -gt 95 ]]
          then
            wxi-content status "Error" "Login Failed"
            wxi-stop
          fi

          TOKEN=$VAULT_LOGIN
          if [[ ${args['0']} == *"cli.sh" || ${args['0']} == *"wx" ]]
          then
            wxi-config write login.token "$TOKEN"
          fi
          export TOKEN
          ;;
        token)
          echo -n "Token: "
          if [[ -n ${args['token']} ]]
          then
            if [[ ${args['token']} != "true" ]]
            then
              TOKEN=${args['token']}
            fi
          elif [[ -n ${config['login.token']} ]]
          then
            TOKEN=${config['login.token']}
          else
            read -s TOKEN
          fi

          if [[ -n $TOKEN ]]
          then
            wxi-content text "***********************************************************************************************"
          fi

          if [[ -z $TOKEN ]]
          then
            wxi-content status "Error" "Token Required"
            wxi-stop
          fi

          if [[ ${#TOKEN} -lt 95 || ${#TOKEN} -gt 95 ]]
          then
            wxi-content status "Error" "Token Invalid"
            wxi-stop
          fi

          VAULT_LOGIN=$(curl https://$VAULT_DOMAIN/v1/auth/token/renew-self -X POST --header "X-Vault-Token: $TOKEN" -d '{ "token": "'$TOKEN'" }' -s | jq -r '.auth.client_token')
          if [[ -z $VAULT_LOGIN || ${#VAULT_LOGIN} -lt 95 || ${#VAULT_LOGIN} -gt 95 ]]
          then
            wxi-content status "Error" "Login Failed"

            if [[ -n ${config['login.token']} ]]
            then
              wx-logout &> /dev/null
              wx-login
            else
              wxi-stop
            fi
          fi

          TOKEN=$VAULT_LOGIN
          if [[ ${args['0']} == *"cli.sh" || ${args['0']} == *"wx" ]]
          then
            wxi-config write login.token "$TOKEN"
          fi
          export TOKEN
          ;;
        *)
          wxi-content status "Error" "Authentication Method Invalid"
          wxi-stop
          ;;
      esac
    fi

    VAULT_USERNAME=$(curl https://$VAULT_DOMAIN/v1/auth/token/lookup-self -X GET --header "X-Vault-Token: $TOKEN" -s | jq -r '.data.display_name')
    if [[ -z $VAULT_USERNAME ]]
    then
      wxi-content status "Error" "Username Missing"
      wxi-stop
    elif [[ $VAULT_USERNAME != ldap* && $VAULT_USERNAME != oidc* ]]
    then
      wxi-content status "Error" "Authentication Method Invalid"
      wxi-stop
    elif [[ $VAULT_USERNAME == ldap* ]]
    then
      USERNAME=${VAULT_USERNAME#ldap-}
    elif [[ $VAULT_USERNAME == oidc* ]]
    then
      USERNAME=${VAULT_USERNAME#oidc-}
    fi

    wxi-ssh-config-sync &> /dev/null
    wxi-ssh-keys-sign &> /dev/null
    wxi-ssh-keys-sync &> /dev/null
  fi
}

wx-logout(){
  wxi-header "Logout"
  wxi-restricted

  if [[ -n ${config['login.token']} ]]
  then
    TOKEN=${config['login.token']}

    VAULT_STATUS=$(curl https://$VAULT_DOMAIN/v1/auth/token/lookup-self -X GET --header "X-Vault-Token: $TOKEN" -s -o /dev/null -w "%{http_code}")
    if [[ $VAULT_STATUS -eq 204 ]]
    then
      wx-login &> /dev/null
      wxi-clean &> /dev/null
    fi

    wxi-header "$ORG_HEADER" h3

    VAULT_STATUS=$(curl https://$VAULT_DOMAIN/v1/auth/token/revoke-self -X POST --header "X-Vault-Token: $TOKEN" -s -o /dev/null -w "%{http_code}")
    if [[ $VAULT_STATUS -eq 204 ]]
    then
      echo "Logging Out..."
    else
      wxi-content status "Error" "Token Expired"
    fi

    wxi-config erase login.token
  fi
}


wxi-args "$@"
wxi-config

echo -n $wxiBold$wxiOrange
cat <<'EOF'

  (`\ .-') /`  ('-.     _  .-')     ('-.       .-') _
   `.( OO ),' ( OO ).-.( \( -O )  _(  OO)     ( OO ) )
,--./  .--.   / . --. / ,------. (,------.,--./ ,--,'
|      |  |   | \-.  \  |   /`. ' |  .---'|   \ |  |\
|  |   |  |,.-'-'  |  | |  /  | | |  |    |    \|  | )
|  |.'.|  |_)\| |_.'  | |  |_.' |(|  '--. |  .     |/
|         |   |  .-.  | |  .  '.' |  .--' |  |\    |
|   ,'.   |   |  | |  | |  |\  \  |  `---.|  | \   |
'--'   '--'   `--' `--' `--' '--' `------'`--'  `--'

EOF
echo -n $wxiNormal

wxi-start
wxi-init
wxi-stop
