#!/bin/bash
###################################################################### 
#Copyright (C) 2022  Kris Occhipinti
#https://filmsbykris.com

#This program is free software: you can redistribute it and/or modify
#it under the terms of the GNU General Public License as published by
#the Free Software Foundation, either version 3 of the License, or
#(at your option) any later version.

#This program is distributed in the hope that it will be useful,
#but WITHOUT ANY WARRANTY; without even the implied warranty of
#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#GNU General Public License for more details.

#You should have received a copy of the GNU General Public License
#along with this program.  If not, see <http://www.gnu.org/licenses/>.
###################################################################### 

mkdir -p "$HOME/.fbk"
conf="$HOME/.fbk/database.conf"

function create_config(){
  read -p "Database User: " user
  read -s -p "Database Password: " password
  echo "user=$user" > "$conf"
  echo "password=$password" >> "$conf"
  echo ""
}

[[ ! -f "$conf" ]] && create_config

source "$conf"

db="$(mysql -u $user -p$password -e "show databases;"|awk '{print $1}')"
db="$(echo "new $db"|tr " " "\n"|fzf --prompt "Select Database:")"

if [[ "$db" == "new" ]] || [[ "$db" == "" ]]
then
  read -p "Enter the name of your Database: " db
  mysql -u $user -p$password -e "CREATE DATABASE $db;"
fi

table="$(mysql -u $user -p$password -e "USE $db;SHOW TABLES;"|awk '{print $1}')"
table="$((echo "new";echo $table|tr " " "\n")|fzf --prompt "Select Table:")"

if [[ "$table" == "new" ]] || [[ "$table" == "" ]]
then
  read -p "Enter the name of your table: " table
fi

cmd="USE $db;"
cmd="${cmd}CREATE TABLE IF NOT EXISTS $table ( id INT AUTO_INCREMENT PRIMARY KEY )"
mysql -u $user -p$password -e "$cmd"

while [ 1 ]
do
  read -p "Item Name: " item
  [[ "$item" == "" ]] && break
  cmd="USE $db;ALTER TABLE $table ADD COLUMN $item TEXT";

  mysql -u $user -p$password -e "$cmd"
done

cmd="USE $db;SHOW COLUMNS FROM $table"
mysql -u $user -p$password -e "$cmd"
